3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
124 function __construct( $conf = array() ) {
125 $this->mConf
= $conf;
126 $this->mTagHooks
= array();
127 $this->mTransparentTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
131 $this->mUrlProtocols
= wfUrlProtocols();
132 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
133 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
134 $this->mVarCache
= array();
135 if ( isset( $conf['preprocessorClass'] ) ) {
136 $this->mPreprocessorClass
= $conf['preprocessorClass'];
137 } elseif ( extension_loaded( 'dom' ) ) {
138 $this->mPreprocessorClass
= 'Preprocessor_DOM';
140 $this->mPreprocessorClass
= 'Preprocessor_Hash';
142 $this->mMarkerIndex
= 0;
143 $this->mFirstCall
= true;
147 * Reduce memory usage to reduce the impact of circular references
149 function __destruct() {
150 if ( isset( $this->mLinkHolders
) ) {
151 $this->mLinkHolders
->__destruct();
153 foreach ( $this as $name => $value ) {
154 unset( $this->$name );
159 * Do various kinds of initialisation on the first call of the parser
161 function firstCallInit() {
162 if ( !$this->mFirstCall
) {
165 $this->mFirstCall
= false;
167 wfProfileIn( __METHOD__
);
169 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
170 CoreParserFunctions
::register( $this );
171 $this->initialiseVariables();
173 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
174 wfProfileOut( __METHOD__
);
182 function clearState() {
183 wfProfileIn( __METHOD__
);
184 if ( $this->mFirstCall
) {
185 $this->firstCallInit();
187 $this->mOutput
= new ParserOutput
;
188 $this->mAutonumber
= 0;
189 $this->mLastSection
= '';
190 $this->mDTopen
= false;
191 $this->mIncludeCount
= array();
192 $this->mStripState
= new StripState
;
193 $this->mArgStack
= false;
194 $this->mInPre
= false;
195 $this->mLinkHolders
= new LinkHolderArray( $this );
197 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
200 * Prefix for temporary replacement strings for the multipass parser.
201 * \x07 should never appear in input as it's disallowed in XML.
202 * Using it at the front also gives us a little extra robustness
203 * since it shouldn't match when butted up against identifier-like
206 * Must not consist of all title characters, or else it will change
207 * the behaviour of <nowiki> in a link.
209 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
210 # Changed to \x7f to allow XML double-parsing -- TS
211 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
214 # Clear these on every parse, bug 4549
215 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
217 $this->mShowToc
= true;
218 $this->mForceTocPosition
= false;
219 $this->mIncludeSizes
= array(
223 $this->mPPNodeCount
= 0;
224 $this->mDefaultSort
= false;
225 $this->mHeadings
= array();
226 $this->mDoubleUnderscores
= array();
227 $this->mExpensiveFunctionCount
= 0;
230 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
231 $this->mPreprocessor
= null;
234 wfRunHooks( 'ParserClearState', array( &$this ) );
235 wfProfileOut( __METHOD__
);
238 function setOutputType( $ot ) {
239 $this->mOutputType
= $ot;
242 'html' => $ot == self
::OT_HTML
,
243 'wiki' => $ot == self
::OT_WIKI
,
244 'pre' => $ot == self
::OT_PREPROCESS
,
249 * Set the context title
251 function setTitle( $t ) {
252 if ( !$t ||
$t instanceof FakeTitle
) {
253 $t = Title
::newFromText( 'NO TITLE' );
255 if ( strval( $t->getFragment() ) !== '' ) {
256 # Strip the fragment to avoid various odd effects
257 $this->mTitle
= clone $t;
258 $this->mTitle
->setFragment( '' );
265 * Accessor for mUniqPrefix.
269 function uniqPrefix() {
270 if( !isset( $this->mUniqPrefix
) ) {
271 // @fixme this is probably *horribly wrong*
272 // LanguageConverter seems to want $wgParser's uniqPrefix, however
273 // if this is called for a parser cache hit, the parser may not
274 // have ever been initialized in the first place.
275 // Not really sure what the heck is supposed to be going on here.
277 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
279 return $this->mUniqPrefix
;
283 * Convert wikitext to HTML
284 * Do not call this function recursively.
286 * @param $text String: text we want to parse
287 * @param $title A title object
288 * @param $options ParserOptions
289 * @param $linestart boolean
290 * @param $clearState boolean
291 * @param $revid Int: number to pass in {{REVISIONID}}
292 * @return ParserOutput a ParserOutput
294 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
296 * First pass--just handle <nowiki> sections, pass the rest off
297 * to internalParse() which does all the real work.
300 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
301 $fname = __METHOD__
.'-' . wfGetCaller();
302 wfProfileIn( __METHOD__
);
303 wfProfileIn( $fname );
309 $this->mOptions
= $options;
310 $this->setTitle( $title );
311 $oldRevisionId = $this->mRevisionId
;
312 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
313 if( $revid !== null ) {
314 $this->mRevisionId
= $revid;
315 $this->mRevisionTimestamp
= null;
317 $this->setOutputType( self
::OT_HTML
);
318 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
320 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
321 $text = $this->internalParse( $text );
322 $text = $this->mStripState
->unstripGeneral( $text );
324 # Clean up special characters, only run once, next-to-last before doBlockLevels
326 # french spaces, last one Guillemet-left
327 # only if there is something before the space
328 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
329 # french spaces, Guillemet-right
330 '/(\\302\\253) /' => '\\1 ',
331 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
333 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
335 $text = $this->doBlockLevels( $text, $linestart );
337 $this->replaceLinkHolders( $text );
339 # the position of the parserConvert() call should not be changed. it
340 # assumes that the links are all replaced and the only thing left
341 # is the <nowiki> mark.
342 # Side-effects: this calls $this->mOutput->setTitleText()
343 $text = $wgContLang->parserConvert( $text, $this );
345 $text = $this->mStripState
->unstripNoWiki( $text );
347 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
349 //!JF Move to its own function
351 $uniq_prefix = $this->mUniqPrefix
;
353 $elements = array_keys( $this->mTransparentTagHooks
);
354 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
356 foreach( $matches as $marker => $data ) {
357 list( $element, $content, $params, $tag ) = $data;
358 $tagName = strtolower( $element );
359 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
360 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
361 array( $content, $params, $this ) );
365 $this->mStripState
->general
->setPair( $marker, $output );
367 $text = $this->mStripState
->unstripGeneral( $text );
369 $text = Sanitizer
::normalizeCharReferences( $text );
371 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
372 $text = self
::tidy($text);
374 # attempt to sanitize at least some nesting problems
375 # (bug #2702 and quite a few others)
377 # ''Something [http://www.cool.com cool''] -->
378 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
379 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
380 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
381 # fix up an anchor inside another anchor, only
382 # at least for a single single nested link (bug 3695)
383 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
384 '\\1\\2</a>\\3</a>\\1\\4</a>',
385 # fix div inside inline elements- doBlockLevels won't wrap a line which
386 # contains a div, so fix it up here; replace
387 # div with escaped text
388 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
389 '\\1\\3<div\\5>\\6</div>\\8\\9',
390 # remove empty italic or bold tag pairs, some
391 # introduced by rules above
392 '/<([bi])><\/\\1>/' => '',
395 $text = preg_replace(
396 array_keys( $tidyregs ),
397 array_values( $tidyregs ),
400 global $wgExpensiveParserFunctionLimit;
401 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
402 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
405 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
407 # Information on include size limits, for the benefit of users who try to skirt them
408 if ( $this->mOptions
->getEnableLimitReport() ) {
409 global $wgExpensiveParserFunctionLimit;
410 $max = $this->mOptions
->getMaxIncludeSize();
411 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
413 "NewPP limit report\n" .
414 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
415 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
416 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
418 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
419 $text .= "\n<!-- \n$limitReport-->\n";
421 $this->mOutput
->setText( $text );
422 $this->mRevisionId
= $oldRevisionId;
423 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
424 wfProfileOut( $fname );
425 wfProfileOut( __METHOD__
);
427 return $this->mOutput
;
431 * Recursive parser entry point that can be called from an extension tag
434 function recursiveTagParse( $text ) {
435 wfProfileIn( __METHOD__
);
436 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
437 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
438 $text = $this->internalParse( $text );
439 wfProfileOut( __METHOD__
);
444 * Expand templates and variables in the text, producing valid, static wikitext.
445 * Also removes comments.
447 function preprocess( $text, $title, $options, $revid = null ) {
448 wfProfileIn( __METHOD__
);
450 $this->setOutputType( self
::OT_PREPROCESS
);
451 $this->mOptions
= $options;
452 $this->setTitle( $title );
453 if( $revid !== null ) {
454 $this->mRevisionId
= $revid;
456 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
457 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
458 $text = $this->replaceVariables( $text );
459 $text = $this->mStripState
->unstripBoth( $text );
460 wfProfileOut( __METHOD__
);
465 * Get a random string
470 function getRandomString() {
471 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
474 function &getTitle() { return $this->mTitle
; }
475 function getOptions() { return $this->mOptions
; }
476 function getRevisionId() { return $this->mRevisionId
; }
477 function getOutput() { return $this->mOutput
; }
478 function nextLinkID() { return $this->mLinkID++
; }
480 function getFunctionLang() {
481 global $wgLang, $wgContLang;
483 $target = $this->mOptions
->getTargetLanguage();
484 if ( $target !== null ) {
487 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
492 * Get a preprocessor object
494 function getPreprocessor() {
495 if ( !isset( $this->mPreprocessor
) ) {
496 $class = $this->mPreprocessorClass
;
497 $this->mPreprocessor
= new $class( $this );
499 return $this->mPreprocessor
;
503 * Replaces all occurrences of HTML-style comments and the given tags
504 * in the text with a random marker and returns the next text. The output
505 * parameter $matches will be an associative array filled with data in
507 * 'UNIQ-xxxxx' => array(
510 * array( 'param' => 'x' ),
511 * '<element param="x">tag content</element>' ) )
513 * @param $elements list of element names. Comments are always extracted.
514 * @param $text Source text string.
515 * @param $uniq_prefix
520 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
525 $taglist = implode( '|', $elements );
526 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
528 while ( '' != $text ) {
529 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
531 if( count( $p ) < 5 ) {
534 if( count( $p ) > 5 ) {
548 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
549 $stripped .= $marker;
551 if ( $close === '/>' ) {
552 // Empty element tag, <tag />
557 if( $element === '!--' ) {
560 $end = "/(<\\/$element\\s*>)/i";
562 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
564 if( count( $q ) < 3 ) {
565 # No end tag -- let it run out to the end of the text.
574 $matches[$marker] = array( $element,
576 Sanitizer
::decodeTagAttributes( $attributes ),
577 "<$element$attributes$close$content$tail" );
583 * Get a list of strippable XML-like elements
585 function getStripList() {
587 $elements = $this->mStripList
;
589 $elements[] = 'html';
591 if( $this->mOptions
->getUseTeX() ) {
592 $elements[] = 'math';
598 * @deprecated use replaceVariables
600 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
605 * Restores pre, math, and other extensions removed by strip()
607 * always call unstripNoWiki() after this one
609 * @deprecated use $this->mStripState->unstrip()
611 function unstrip( $text, $state ) {
612 return $state->unstripGeneral( $text );
616 * Always call this after unstrip() to preserve the order
619 * @deprecated use $this->mStripState->unstrip()
621 function unstripNoWiki( $text, $state ) {
622 return $state->unstripNoWiki( $text );
626 * @deprecated use $this->mStripState->unstripBoth()
628 function unstripForHTML( $text ) {
629 return $this->mStripState
->unstripBoth( $text );
633 * Add an item to the strip state
634 * Returns the unique tag which must be inserted into the stripped text
635 * The tag will be replaced with the original text in unstrip()
639 function insertStripItem( $text ) {
640 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
641 $this->mMarkerIndex++
;
642 $this->mStripState
->general
->setPair( $rnd, $text );
647 * Interface with html tidy, used if $wgUseTidy = true.
648 * If tidy isn't able to correct the markup, the original will be
649 * returned in all its glory with a warning comment appended.
651 * Either the external tidy program or the in-process tidy extension
652 * will be used depending on availability. Override the default
653 * $wgTidyInternal setting to disable the internal if it's not working.
655 * @param string $text Hideous HTML input
656 * @return string Corrected HTML output
660 function tidy( $text ) {
661 global $wgTidyInternal;
662 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
663 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
664 '<head><title>test</title></head><body>'.$text.'</body></html>';
665 if( $wgTidyInternal ) {
666 $correctedtext = self
::internalTidy( $wrappedtext );
668 $correctedtext = self
::externalTidy( $wrappedtext );
670 if( is_null( $correctedtext ) ) {
671 wfDebug( "Tidy error detected!\n" );
672 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
674 return $correctedtext;
678 * Spawn an external HTML tidy process and get corrected markup back from it.
683 function externalTidy( $text ) {
684 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
685 wfProfileIn( __METHOD__
);
690 $descriptorspec = array(
691 0 => array('pipe', 'r'),
692 1 => array('pipe', 'w'),
693 2 => array('file', wfGetNull(), 'a')
696 if( function_exists('proc_open') ) {
697 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
698 if (is_resource($process)) {
699 // Theoretically, this style of communication could cause a deadlock
700 // here. If the stdout buffer fills up, then writes to stdin could
701 // block. This doesn't appear to happen with tidy, because tidy only
702 // writes to stdout after it's finished reading from stdin. Search
703 // for tidyParseStdin and tidySaveStdout in console/tidy.c
704 fwrite($pipes[0], $text);
706 while (!feof($pipes[1])) {
707 $cleansource .= fgets($pipes[1], 1024);
710 proc_close($process);
714 wfProfileOut( __METHOD__
);
716 if( $cleansource == '' && $text != '') {
717 // Some kind of error happened, so we couldn't get the corrected text.
718 // Just give up; we'll use the source text and append a warning.
726 * Use the HTML tidy PECL extension to use the tidy library in-process,
727 * saving the overhead of spawning a new process.
729 * 'pear install tidy' should be able to compile the extension module.
734 function internalTidy( $text ) {
735 global $wgTidyConf, $IP, $wgDebugTidy;
736 wfProfileIn( __METHOD__
);
739 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
740 $tidy->cleanRepair();
741 if( $tidy->getStatus() == 2 ) {
742 // 2 is magic number for fatal error
743 // http://www.php.net/manual/en/function.tidy-get-status.php
746 $cleansource = tidy_get_output( $tidy );
748 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
749 $cleansource .= "<!--\nTidy reports:\n" .
750 str_replace( '-->', '-->', $tidy->errorBuffer
) .
754 wfProfileOut( __METHOD__
);
759 * parse the wiki syntax used to render tables
763 function doTableStuff ( $text ) {
764 wfProfileIn( __METHOD__
);
766 $lines = StringUtils
::explode( "\n", $text );
768 $td_history = array (); // Is currently a td tag open?
769 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
770 $tr_history = array (); // Is currently a tr tag open?
771 $tr_attributes = array (); // history of tr attributes
772 $has_opened_tr = array(); // Did this table open a <tr> element?
773 $indent_level = 0; // indent level of the table
775 foreach ( $lines as $outLine ) {
776 $line = trim( $outLine );
778 if( $line == '' ) { // empty line, go to next line
779 $out .= $outLine."\n";
782 $first_character = $line[0];
785 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
786 // First check if we are starting a new table
787 $indent_level = strlen( $matches[1] );
789 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
790 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
792 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
793 array_push ( $td_history , false );
794 array_push ( $last_tag_history , '' );
795 array_push ( $tr_history , false );
796 array_push ( $tr_attributes , '' );
797 array_push ( $has_opened_tr , false );
798 } else if ( count ( $td_history ) == 0 ) {
799 // Don't do any of the following
800 $out .= $outLine."\n";
802 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
803 // We are ending a table
804 $line = '</table>' . substr ( $line , 2 );
805 $last_tag = array_pop ( $last_tag_history );
807 if ( !array_pop ( $has_opened_tr ) ) {
808 $line = "<tr><td></td></tr>{$line}";
811 if ( array_pop ( $tr_history ) ) {
812 $line = "</tr>{$line}";
815 if ( array_pop ( $td_history ) ) {
816 $line = "</{$last_tag}>{$line}";
818 array_pop ( $tr_attributes );
819 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
820 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
821 // Now we have a table row
822 $line = preg_replace( '#^\|-+#', '', $line );
824 // Whats after the tag is now only attributes
825 $attributes = $this->mStripState
->unstripBoth( $line );
826 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
827 array_pop ( $tr_attributes );
828 array_push ( $tr_attributes , $attributes );
831 $last_tag = array_pop ( $last_tag_history );
832 array_pop ( $has_opened_tr );
833 array_push ( $has_opened_tr , true );
835 if ( array_pop ( $tr_history ) ) {
839 if ( array_pop ( $td_history ) ) {
840 $line = "</{$last_tag}>{$line}";
844 array_push ( $tr_history , false );
845 array_push ( $td_history , false );
846 array_push ( $last_tag_history , '' );
848 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
849 // This might be cell elements, td, th or captions
850 if ( substr ( $line , 0 , 2 ) === '|+' ) {
851 $first_character = '+';
852 $line = substr ( $line , 1 );
855 $line = substr ( $line , 1 );
857 if ( $first_character === '!' ) {
858 $line = str_replace ( '!!' , '||' , $line );
861 // Split up multiple cells on the same line.
862 // FIXME : This can result in improper nesting of tags processed
863 // by earlier parser steps, but should avoid splitting up eg
864 // attribute values containing literal "||".
865 $cells = StringUtils
::explodeMarkup( '||' , $line );
869 // Loop through each table cell
870 foreach ( $cells as $cell )
873 if ( $first_character !== '+' )
875 $tr_after = array_pop ( $tr_attributes );
876 if ( !array_pop ( $tr_history ) ) {
877 $previous = "<tr{$tr_after}>\n";
879 array_push ( $tr_history , true );
880 array_push ( $tr_attributes , '' );
881 array_pop ( $has_opened_tr );
882 array_push ( $has_opened_tr , true );
885 $last_tag = array_pop ( $last_tag_history );
887 if ( array_pop ( $td_history ) ) {
888 $previous = "</{$last_tag}>{$previous}";
891 if ( $first_character === '|' ) {
893 } else if ( $first_character === '!' ) {
895 } else if ( $first_character === '+' ) {
896 $last_tag = 'caption';
901 array_push ( $last_tag_history , $last_tag );
903 // A cell could contain both parameters and data
904 $cell_data = explode ( '|' , $cell , 2 );
906 // Bug 553: Note that a '|' inside an invalid link should not
907 // be mistaken as delimiting cell parameters
908 if ( strpos( $cell_data[0], '[[' ) !== false ) {
909 $cell = "{$previous}<{$last_tag}>{$cell}";
910 } else if ( count ( $cell_data ) == 1 )
911 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
913 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
914 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
915 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
919 array_push ( $td_history , true );
922 $out .= $outLine . "\n";
925 // Closing open td, tr && table
926 while ( count ( $td_history ) > 0 )
928 if ( array_pop ( $td_history ) ) {
931 if ( array_pop ( $tr_history ) ) {
934 if ( !array_pop ( $has_opened_tr ) ) {
935 $out .= "<tr><td></td></tr>\n" ;
938 $out .= "</table>\n";
941 // Remove trailing line-ending (b/c)
942 if ( substr( $out, -1 ) === "\n" ) {
943 $out = substr( $out, 0, -1 );
946 // special case: don't return empty table
947 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
951 wfProfileOut( __METHOD__
);
957 * Helper function for parse() that transforms wiki markup into
958 * HTML. Only called for $mOutputType == self::OT_HTML.
962 function internalParse( $text ) {
964 wfProfileIn( __METHOD__
);
966 # Hook to suspend the parser in this state
967 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
968 wfProfileOut( __METHOD__
);
972 $text = $this->replaceVariables( $text );
973 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
974 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
976 // Tables need to come after variable replacement for things to work
977 // properly; putting them before other transformations should keep
978 // exciting things like link expansions from showing up in surprising
980 $text = $this->doTableStuff( $text );
982 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
984 $text = $this->doDoubleUnderscore( $text );
985 $text = $this->doHeadings( $text );
986 if($this->mOptions
->getUseDynamicDates()) {
987 $df = DateFormatter
::getInstance();
988 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
990 $text = $this->doAllQuotes( $text );
991 $text = $this->replaceInternalLinks( $text );
992 $text = $this->replaceExternalLinks( $text );
994 # replaceInternalLinks may sometimes leave behind
995 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
996 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
998 $text = $this->doMagicLinks( $text );
999 $text = $this->formatHeadings( $text, $isMain );
1001 wfProfileOut( __METHOD__
);
1006 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1007 * magic external links.
1012 function doMagicLinks( $text ) {
1013 wfProfileIn( __METHOD__
);
1014 $prots = $this->mUrlProtocols
;
1015 $urlChar = self
::EXT_LINK_URL_CLASS
;
1016 $text = preg_replace_callback(
1018 (<a.*?</a>) | # m[1]: Skip link text
1019 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1020 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1021 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1022 ISBN\s+(\b # m[5]: ISBN, capture number
1023 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1024 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1025 [0-9Xx] # check digit
1027 )!x', array( &$this, 'magicLinkCallback' ), $text );
1028 wfProfileOut( __METHOD__
);
1032 function magicLinkCallback( $m ) {
1033 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1036 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1039 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1040 # Free external link
1041 return $this->makeFreeExternalLink( $m[0] );
1042 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1044 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1048 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1050 $urlmsg = 'pubmedurl';
1053 throw new MWException( __METHOD__
.': unrecognised match type "' .
1054 substr($m[0], 0, 20 ) . '"' );
1056 $url = wfMsg( $urlmsg, $id);
1057 $sk = $this->mOptions
->getSkin();
1058 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1059 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1060 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1063 $num = strtr( $isbn, array(
1068 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1070 $titleObj->escapeLocalUrl() .
1071 "\" class=\"internal\">ISBN $isbn</a>";
1078 * Make a free external link, given a user-supplied URL
1082 function makeFreeExternalLink( $url ) {
1084 wfProfileIn( __METHOD__
);
1086 $sk = $this->mOptions
->getSkin();
1089 # The characters '<' and '>' (which were escaped by
1090 # removeHTMLtags()) should not be included in
1091 # URLs, per RFC 2396.
1093 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1094 $trail = substr($url, $m2[0][1]) . $trail;
1095 $url = substr($url, 0, $m2[0][1]);
1098 # Move trailing punctuation to $trail
1100 # If there is no left bracket, then consider right brackets fair game too
1101 if ( strpos( $url, '(' ) === false ) {
1105 $numSepChars = strspn( strrev( $url ), $sep );
1106 if ( $numSepChars ) {
1107 $trail = substr( $url, -$numSepChars ) . $trail;
1108 $url = substr( $url, 0, -$numSepChars );
1111 $url = Sanitizer
::cleanUrl( $url );
1113 # Is this an external image?
1114 $text = $this->maybeMakeExternalImage( $url );
1115 if ( $text === false ) {
1116 # Not an image, make a link
1117 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1118 # Register it in the output object...
1119 # Replace unnecessary URL escape codes with their equivalent characters
1120 $pasteurized = self
::replaceUnusualEscapes( $url );
1121 $this->mOutput
->addExternalLink( $pasteurized );
1123 wfProfileOut( __METHOD__
);
1124 return $text . $trail;
1129 * Parse headers and return html
1133 function doHeadings( $text ) {
1134 wfProfileIn( __METHOD__
);
1135 for ( $i = 6; $i >= 1; --$i ) {
1136 $h = str_repeat( '=', $i );
1137 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1138 "<h$i>\\1</h$i>", $text );
1140 wfProfileOut( __METHOD__
);
1145 * Replace single quotes with HTML markup
1147 * @return string the altered text
1149 function doAllQuotes( $text ) {
1150 wfProfileIn( __METHOD__
);
1152 $lines = StringUtils
::explode( "\n", $text );
1153 foreach ( $lines as $line ) {
1154 $outtext .= $this->doQuotes( $line ) . "\n";
1156 $outtext = substr($outtext, 0,-1);
1157 wfProfileOut( __METHOD__
);
1162 * Helper function for doAllQuotes()
1164 public function doQuotes( $text ) {
1165 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1166 if ( count( $arr ) == 1 )
1170 # First, do some preliminary work. This may shift some apostrophes from
1171 # being mark-up to being text. It also counts the number of occurrences
1172 # of bold and italics mark-ups.
1176 foreach ( $arr as $r )
1178 if ( ( $i %
2 ) == 1 )
1180 # If there are ever four apostrophes, assume the first is supposed to
1181 # be text, and the remaining three constitute mark-up for bold text.
1182 if ( strlen( $arr[$i] ) == 4 )
1187 # If there are more than 5 apostrophes in a row, assume they're all
1188 # text except for the last 5.
1189 else if ( strlen( $arr[$i] ) > 5 )
1191 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1194 # Count the number of occurrences of bold and italics mark-ups.
1195 # We are not counting sequences of five apostrophes.
1196 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1197 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1198 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1203 # If there is an odd number of both bold and italics, it is likely
1204 # that one of the bold ones was meant to be an apostrophe followed
1205 # by italics. Which one we cannot know for certain, but it is more
1206 # likely to be one that has a single-letter word before it.
1207 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1210 $firstsingleletterword = -1;
1211 $firstmultiletterword = -1;
1213 foreach ( $arr as $r )
1215 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1217 $x1 = substr ($arr[$i-1], -1);
1218 $x2 = substr ($arr[$i-1], -2, 1);
1220 if ($firstspace == -1) $firstspace = $i;
1221 } else if ($x2 === ' ') {
1222 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1224 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1230 # If there is a single-letter word, use it!
1231 if ($firstsingleletterword > -1)
1233 $arr [ $firstsingleletterword ] = "''";
1234 $arr [ $firstsingleletterword-1 ] .= "'";
1236 # If not, but there's a multi-letter word, use that one.
1237 else if ($firstmultiletterword > -1)
1239 $arr [ $firstmultiletterword ] = "''";
1240 $arr [ $firstmultiletterword-1 ] .= "'";
1242 # ... otherwise use the first one that has neither.
1243 # (notice that it is possible for all three to be -1 if, for example,
1244 # there is only one pentuple-apostrophe in the line)
1245 else if ($firstspace > -1)
1247 $arr [ $firstspace ] = "''";
1248 $arr [ $firstspace-1 ] .= "'";
1252 # Now let's actually convert our apostrophic mush to HTML!
1257 foreach ($arr as $r)
1261 if ($state === 'both')
1268 if (strlen ($r) == 2)
1271 { $output .= '</i>'; $state = ''; }
1272 else if ($state === 'bi')
1273 { $output .= '</i>'; $state = 'b'; }
1274 else if ($state === 'ib')
1275 { $output .= '</b></i><b>'; $state = 'b'; }
1276 else if ($state === 'both')
1277 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1278 else # $state can be 'b' or ''
1279 { $output .= '<i>'; $state .= 'i'; }
1281 else if (strlen ($r) == 3)
1284 { $output .= '</b>'; $state = ''; }
1285 else if ($state === 'bi')
1286 { $output .= '</i></b><i>'; $state = 'i'; }
1287 else if ($state === 'ib')
1288 { $output .= '</b>'; $state = 'i'; }
1289 else if ($state === 'both')
1290 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1291 else # $state can be 'i' or ''
1292 { $output .= '<b>'; $state .= 'b'; }
1294 else if (strlen ($r) == 5)
1297 { $output .= '</b><i>'; $state = 'i'; }
1298 else if ($state === 'i')
1299 { $output .= '</i><b>'; $state = 'b'; }
1300 else if ($state === 'bi')
1301 { $output .= '</i></b>'; $state = ''; }
1302 else if ($state === 'ib')
1303 { $output .= '</b></i>'; $state = ''; }
1304 else if ($state === 'both')
1305 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1306 else # ($state == '')
1307 { $buffer = ''; $state = 'both'; }
1312 # Now close all remaining tags. Notice that the order is important.
1313 if ($state === 'b' ||
$state === 'ib')
1315 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1317 if ($state === 'bi')
1319 # There might be lonely ''''', so make sure we have a buffer
1320 if ($state === 'both' && $buffer)
1321 $output .= '<b><i>'.$buffer.'</i></b>';
1327 * Replace external links (REL)
1329 * Note: this is all very hackish and the order of execution matters a lot.
1330 * Make sure to run maintenance/parserTests.php if you change this code.
1334 function replaceExternalLinks( $text ) {
1336 wfProfileIn( __METHOD__
);
1338 $sk = $this->mOptions
->getSkin();
1340 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1341 $s = array_shift( $bits );
1344 while ( $i<count( $bits ) ) {
1346 $protocol = $bits[$i++
];
1347 $text = $bits[$i++
];
1348 $trail = $bits[$i++
];
1350 # The characters '<' and '>' (which were escaped by
1351 # removeHTMLtags()) should not be included in
1352 # URLs, per RFC 2396.
1354 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1355 $text = substr($url, $m2[0][1]) . ' ' . $text;
1356 $url = substr($url, 0, $m2[0][1]);
1359 # If the link text is an image URL, replace it with an <img> tag
1360 # This happened by accident in the original parser, but some people used it extensively
1361 $img = $this->maybeMakeExternalImage( $text );
1362 if ( $img !== false ) {
1368 # Set linktype for CSS - if URL==text, link is essentially free
1369 $linktype = ($text === $url) ?
'free' : 'text';
1371 # No link text, e.g. [http://domain.tld/some.link]
1372 if ( $text == '' ) {
1373 # Autonumber if allowed. See bug #5918
1374 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1375 $text = '[' . ++
$this->mAutonumber
. ']';
1376 $linktype = 'autonumber';
1378 # Otherwise just use the URL
1379 $text = htmlspecialchars( $url );
1383 # Have link text, e.g. [http://domain.tld/some.link text]s
1385 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1388 $text = $wgContLang->markNoConversion($text);
1390 $url = Sanitizer
::cleanUrl( $url );
1392 # Use the encoded URL
1393 # This means that users can paste URLs directly into the text
1394 # Funny characters like ö aren't valid in URLs anyway
1395 # This was changed in August 2004
1396 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1398 # Register link in the output object.
1399 # Replace unnecessary URL escape codes with the referenced character
1400 # This prevents spammers from hiding links from the filters
1401 $pasteurized = self
::replaceUnusualEscapes( $url );
1402 $this->mOutput
->addExternalLink( $pasteurized );
1405 wfProfileOut( __METHOD__
);
1410 * Replace unusual URL escape codes with their equivalent characters
1414 * @todo This can merge genuinely required bits in the path or query string,
1415 * breaking legit URLs. A proper fix would treat the various parts of
1416 * the URL differently; as a workaround, just use the output for
1417 * statistical records, not for actual linking/output.
1419 static function replaceUnusualEscapes( $url ) {
1420 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1421 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1425 * Callback function used in replaceUnusualEscapes().
1426 * Replaces unusual URL escape codes with their equivalent character
1430 private static function replaceUnusualEscapesCallback( $matches ) {
1431 $char = urldecode( $matches[0] );
1432 $ord = ord( $char );
1433 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1434 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1435 // No, shouldn't be escaped
1438 // Yes, leave it escaped
1444 * make an image if it's allowed, either through the global
1445 * option or through the exception
1448 function maybeMakeExternalImage( $url ) {
1449 $sk = $this->mOptions
->getSkin();
1450 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1451 $imagesexception = !empty($imagesfrom);
1453 if ( $this->mOptions
->getAllowExternalImages()
1454 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1455 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1457 $text = $sk->makeExternalImage( $url );
1464 * Process [[ ]] wikilinks
1465 * @return processed text
1469 function replaceInternalLinks( $s ) {
1470 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1475 * Process [[ ]] wikilinks (RIL)
1476 * @return LinkHolderArray
1480 function replaceInternalLinks2( &$s ) {
1483 wfProfileIn( __METHOD__
);
1485 wfProfileIn( __METHOD__
.'-setup' );
1486 static $tc = FALSE, $e1, $e1_img;
1487 # the % is needed to support urlencoded titles as well
1489 $tc = Title
::legalChars() . '#%';
1490 # Match a link having the form [[namespace:link|alternate]]trail
1491 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1492 # Match cases where there is no "]]", which might still be images
1493 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1496 $sk = $this->mOptions
->getSkin();
1497 $holders = new LinkHolderArray( $this );
1499 #split the entire text string on occurences of [[
1500 $a = StringUtils
::explode( '[[', ' ' . $s );
1501 #get the first element (all text up to first [[), and remove the space we added
1504 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1505 $s = substr( $s, 1 );
1507 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1509 if ( $useLinkPrefixExtension ) {
1510 # Match the end of a line for a word that's not followed by whitespace,
1511 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1512 $e2 = wfMsgForContent( 'linkprefix' );
1515 if( is_null( $this->mTitle
) ) {
1516 wfProfileOut( __METHOD__
.'-setup' );
1517 wfProfileOut( __METHOD__
);
1518 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1520 $nottalk = !$this->mTitle
->isTalkPage();
1522 if ( $useLinkPrefixExtension ) {
1524 if ( preg_match( $e2, $s, $m ) ) {
1525 $first_prefix = $m[2];
1527 $first_prefix = false;
1533 if($wgContLang->hasVariants()) {
1534 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1536 $selflink = array($this->mTitle
->getPrefixedText());
1538 $useSubpages = $this->areSubpagesAllowed();
1539 wfProfileOut( __METHOD__
.'-setup' );
1541 # Loop for each link
1542 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1543 # Check for excessive memory usage
1544 if ( $holders->isBig() ) {
1546 # Do the existence check, replace the link holders and clear the array
1547 $holders->replace( $s );
1551 if ( $useLinkPrefixExtension ) {
1552 wfProfileIn( __METHOD__
.'-prefixhandling' );
1553 if ( preg_match( $e2, $s, $m ) ) {
1561 $prefix = $first_prefix;
1562 $first_prefix = false;
1564 wfProfileOut( __METHOD__
.'-prefixhandling' );
1567 $might_be_img = false;
1569 wfProfileIn( __METHOD__
."-e1" );
1570 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1572 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1573 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1574 # the real problem is with the $e1 regex
1577 # Still some problems for cases where the ] is meant to be outside punctuation,
1578 # and no image is in sight. See bug 2095.
1581 substr( $m[3], 0, 1 ) === ']' &&
1582 strpos($text, '[') !== false
1585 $text .= ']'; # so that replaceExternalLinks($text) works later
1586 $m[3] = substr( $m[3], 1 );
1588 # fix up urlencoded title texts
1589 if( strpos( $m[1], '%' ) !== false ) {
1590 # Should anchors '#' also be rejected?
1591 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1594 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1595 $might_be_img = true;
1597 if ( strpos( $m[1], '%' ) !== false ) {
1598 $m[1] = urldecode($m[1]);
1601 } else { # Invalid form; output directly
1602 $s .= $prefix . '[[' . $line ;
1603 wfProfileOut( __METHOD__
."-e1" );
1606 wfProfileOut( __METHOD__
."-e1" );
1607 wfProfileIn( __METHOD__
."-misc" );
1609 # Don't allow internal links to pages containing
1610 # PROTO: where PROTO is a valid URL protocol; these
1611 # should be external links.
1612 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1613 $s .= $prefix . '[[' . $line ;
1614 wfProfileOut( __METHOD__
."-misc" );
1618 # Make subpage if necessary
1619 if( $useSubpages ) {
1620 $link = $this->maybeDoSubpageLink( $m[1], $text );
1625 $noforce = (substr($m[1], 0, 1) !== ':');
1627 # Strip off leading ':'
1628 $link = substr($link, 1);
1631 wfProfileOut( __METHOD__
."-misc" );
1632 wfProfileIn( __METHOD__
."-title" );
1633 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1635 $s .= $prefix . '[[' . $line;
1636 wfProfileOut( __METHOD__
."-title" );
1640 $ns = $nt->getNamespace();
1641 $iw = $nt->getInterWiki();
1642 wfProfileOut( __METHOD__
."-title" );
1644 if ($might_be_img) { # if this is actually an invalid link
1645 wfProfileIn( __METHOD__
."-might_be_img" );
1646 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1649 #look at the next 'line' to see if we can close it there
1651 $next_line = $a->current();
1652 if ( $next_line === false ||
$next_line === null ) {
1655 $m = explode( ']]', $next_line, 3 );
1656 if ( count( $m ) == 3 ) {
1657 # the first ]] closes the inner link, the second the image
1659 $text .= "[[{$m[0]}]]{$m[1]}";
1662 } elseif ( count( $m ) == 2 ) {
1663 #if there's exactly one ]] that's fine, we'll keep looking
1664 $text .= "[[{$m[0]}]]{$m[1]}";
1666 #if $next_line is invalid too, we need look no further
1667 $text .= '[[' . $next_line;
1672 # we couldn't find the end of this imageLink, so output it raw
1673 #but don't ignore what might be perfectly normal links in the text we've examined
1674 $holders->merge( $this->replaceInternalLinks2( $text ) );
1675 $s .= "{$prefix}[[$link|$text";
1676 # note: no $trail, because without an end, there *is* no trail
1677 wfProfileOut( __METHOD__
."-might_be_img" );
1680 } else { #it's not an image, so output it raw
1681 $s .= "{$prefix}[[$link|$text";
1682 # note: no $trail, because without an end, there *is* no trail
1683 wfProfileOut( __METHOD__
."-might_be_img" );
1686 wfProfileOut( __METHOD__
."-might_be_img" );
1689 $wasblank = ( '' == $text );
1690 if( $wasblank ) $text = $link;
1692 # Link not escaped by : , create the various objects
1696 wfProfileIn( __METHOD__
."-interwiki" );
1697 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1698 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1699 $s = rtrim($s . $prefix);
1700 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1701 wfProfileOut( __METHOD__
."-interwiki" );
1704 wfProfileOut( __METHOD__
."-interwiki" );
1706 if ( $ns == NS_IMAGE
) {
1707 wfProfileIn( __METHOD__
."-image" );
1708 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1709 # recursively parse links inside the image caption
1710 # actually, this will parse them in any other parameters, too,
1711 # but it might be hard to fix that, and it doesn't matter ATM
1712 $text = $this->replaceExternalLinks($text);
1713 $holders->merge( $this->replaceInternalLinks2( $text ) );
1715 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1716 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1718 $this->mOutput
->addImage( $nt->getDBkey() );
1719 wfProfileOut( __METHOD__
."-image" );
1724 if ( $ns == NS_CATEGORY
) {
1725 wfProfileIn( __METHOD__
."-category" );
1726 $s = rtrim($s . "\n"); # bug 87
1729 $sortkey = $this->getDefaultSort();
1733 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1734 $sortkey = str_replace( "\n", '', $sortkey );
1735 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1736 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1739 * Strip the whitespace Category links produce, see bug 87
1740 * @todo We might want to use trim($tmp, "\n") here.
1742 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1744 wfProfileOut( __METHOD__
."-category" );
1749 # Self-link checking
1750 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1751 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1752 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1757 # Special and Media are pseudo-namespaces; no pages actually exist in them
1758 if( $ns == NS_MEDIA
) {
1759 # Give extensions a chance to select the file revision for us
1760 $skip = $time = false;
1761 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1763 $link = $sk->link( $nt );
1765 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1767 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1768 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1771 } elseif( $ns == NS_SPECIAL
) {
1772 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1773 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1775 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1778 } elseif( $ns == NS_IMAGE
) {
1779 $img = wfFindFile( $nt );
1781 // Force a blue link if the file exists; may be a remote
1782 // upload on the shared repository, and we want to see its
1783 // auto-generated page.
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1785 $this->mOutput
->addLink( $nt );
1789 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1791 wfProfileOut( __METHOD__
);
1796 * Make a link placeholder. The text returned can be later resolved to a real link with
1797 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1798 * parsing of interwiki links, and secondly to allow all existence checks and
1799 * article length checks (for stub links) to be bundled into a single query.
1803 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1804 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1808 * Render a forced-blue link inline; protect against double expansion of
1809 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1810 * Since this little disaster has to split off the trail text to avoid
1811 * breaking URLs in the following text without breaking trails on the
1812 * wiki links, it's been made into a horrible function.
1815 * @param string $text
1816 * @param string $query
1817 * @param string $trail
1818 * @param string $prefix
1819 * @return string HTML-wikitext mix oh yuck
1821 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1822 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1823 $sk = $this->mOptions
->getSkin();
1824 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1825 return $this->armorLinks( $link ) . $trail;
1829 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1830 * going to go through further parsing steps before inline URL expansion.
1832 * Not needed quite as much as it used to be since free links are a bit
1833 * more sensible these days. But bracketed links are still an issue.
1835 * @param string more-or-less HTML
1836 * @return string less-or-more HTML with NOPARSE bits
1838 function armorLinks( $text ) {
1839 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1840 "{$this->mUniqPrefix}NOPARSE$1", $text );
1844 * Return true if subpage links should be expanded on this page.
1847 function areSubpagesAllowed() {
1848 # Some namespaces don't allow subpages
1849 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1853 * Handle link to subpage if necessary
1854 * @param string $target the source of the link
1855 * @param string &$text the link text, modified as necessary
1856 * @return string the full name of the link
1859 function maybeDoSubpageLink($target, &$text) {
1862 # :Foobar -- override special treatment of prefix (images, language links)
1863 # /Foobar -- convert to CurrentPage/Foobar
1864 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1865 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1866 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1868 wfProfileIn( __METHOD__
);
1869 $ret = $target; # default return value is no change
1871 # Some namespaces don't allow subpages,
1872 # so only perform processing if subpages are allowed
1873 if( $this->areSubpagesAllowed() ) {
1874 $hash = strpos( $target, '#' );
1875 if( $hash !== false ) {
1876 $suffix = substr( $target, $hash );
1877 $target = substr( $target, 0, $hash );
1882 $target = trim( $target );
1883 # Look at the first character
1884 if( $target != '' && $target{0} === '/' ) {
1885 # / at end means we don't want the slash to be shown
1887 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1888 if( $trailingSlashes ) {
1889 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1891 $noslash = substr( $target, 1 );
1894 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1895 if( '' === $text ) {
1896 $text = $target . $suffix;
1897 } # this might be changed for ugliness reasons
1899 # check for .. subpage backlinks
1901 $nodotdot = $target;
1902 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1904 $nodotdot = substr( $nodotdot, 3 );
1906 if($dotdotcount > 0) {
1907 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1908 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1909 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1910 # / at the end means don't show full path
1911 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1912 $nodotdot = substr( $nodotdot, 0, -1 );
1913 if( '' === $text ) {
1914 $text = $nodotdot . $suffix;
1917 $nodotdot = trim( $nodotdot );
1918 if( $nodotdot != '' ) {
1919 $ret .= '/' . $nodotdot;
1927 wfProfileOut( __METHOD__
);
1932 * Used by doBlockLevels()
1935 /* private */ function closeParagraph() {
1937 if ( '' != $this->mLastSection
) {
1938 $result = '</' . $this->mLastSection
. ">\n";
1940 $this->mInPre
= false;
1941 $this->mLastSection
= '';
1944 # getCommon() returns the length of the longest common substring
1945 # of both arguments, starting at the beginning of both.
1947 /* private */ function getCommon( $st1, $st2 ) {
1948 $fl = strlen( $st1 );
1949 $shorter = strlen( $st2 );
1950 if ( $fl < $shorter ) { $shorter = $fl; }
1952 for ( $i = 0; $i < $shorter; ++
$i ) {
1953 if ( $st1{$i} != $st2{$i} ) { break; }
1957 # These next three functions open, continue, and close the list
1958 # element appropriate to the prefix character passed into them.
1960 /* private */ function openList( $char ) {
1961 $result = $this->closeParagraph();
1963 if ( '*' === $char ) { $result .= '<ul><li>'; }
1964 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1965 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1966 else if ( ';' === $char ) {
1967 $result .= '<dl><dt>';
1968 $this->mDTopen
= true;
1970 else { $result = '<!-- ERR 1 -->'; }
1975 /* private */ function nextItem( $char ) {
1976 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1977 else if ( ':' === $char ||
';' === $char ) {
1979 if ( $this->mDTopen
) { $close = '</dt>'; }
1980 if ( ';' === $char ) {
1981 $this->mDTopen
= true;
1982 return $close . '<dt>';
1984 $this->mDTopen
= false;
1985 return $close . '<dd>';
1988 return '<!-- ERR 2 -->';
1991 /* private */ function closeList( $char ) {
1992 if ( '*' === $char ) { $text = '</li></ul>'; }
1993 else if ( '#' === $char ) { $text = '</li></ol>'; }
1994 else if ( ':' === $char ) {
1995 if ( $this->mDTopen
) {
1996 $this->mDTopen
= false;
1997 $text = '</dt></dl>';
1999 $text = '</dd></dl>';
2002 else { return '<!-- ERR 3 -->'; }
2008 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2011 * @return string the lists rendered as HTML
2013 function doBlockLevels( $text, $linestart ) {
2014 wfProfileIn( __METHOD__
);
2016 # Parsing through the text line by line. The main thing
2017 # happening here is handling of block-level elements p, pre,
2018 # and making lists from lines starting with * # : etc.
2020 $textLines = StringUtils
::explode( "\n", $text );
2022 $lastPrefix = $output = '';
2023 $this->mDTopen
= $inBlockElem = false;
2025 $paragraphStack = false;
2027 foreach ( $textLines as $oLine ) {
2029 if ( !$linestart ) {
2035 $lastPrefixLength = strlen( $lastPrefix );
2036 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2037 $preOpenMatch = preg_match('/<pre/i', $oLine );
2038 if ( !$this->mInPre
) {
2039 # Multiple prefixes may abut each other for nested lists.
2040 $prefixLength = strspn( $oLine, '*#:;' );
2041 $prefix = substr( $oLine, 0, $prefixLength );
2044 $prefix2 = str_replace( ';', ':', $prefix );
2045 $t = substr( $oLine, $prefixLength );
2046 $this->mInPre
= (bool)$preOpenMatch;
2048 # Don't interpret any other prefixes in preformatted text
2050 $prefix = $prefix2 = '';
2055 if( $prefixLength && $lastPrefix === $prefix2 ) {
2056 # Same as the last item, so no need to deal with nesting or opening stuff
2057 $output .= $this->nextItem( substr( $prefix, -1 ) );
2058 $paragraphStack = false;
2060 if ( substr( $prefix, -1 ) === ';') {
2061 # The one nasty exception: definition lists work like this:
2062 # ; title : definition text
2063 # So we check for : in the remainder text to split up the
2064 # title and definition, without b0rking links.
2066 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2068 $output .= $term . $this->nextItem( ':' );
2071 } elseif( $prefixLength ||
$lastPrefixLength ) {
2072 # Either open or close a level...
2073 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2074 $paragraphStack = false;
2076 while( $commonPrefixLength < $lastPrefixLength ) {
2077 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2078 --$lastPrefixLength;
2080 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2081 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2083 while ( $prefixLength > $commonPrefixLength ) {
2084 $char = substr( $prefix, $commonPrefixLength, 1 );
2085 $output .= $this->openList( $char );
2087 if ( ';' === $char ) {
2088 # FIXME: This is dupe of code above
2089 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2091 $output .= $term . $this->nextItem( ':' );
2094 ++
$commonPrefixLength;
2096 $lastPrefix = $prefix2;
2098 if( 0 == $prefixLength ) {
2099 wfProfileIn( __METHOD__
."-paragraph" );
2100 # No prefix (not in list)--go to paragraph mode
2101 // XXX: use a stack for nestable elements like span, table and div
2102 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2103 $closematch = preg_match(
2104 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2105 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2106 if ( $openmatch or $closematch ) {
2107 $paragraphStack = false;
2108 #Â TODO bug 5718: paragraph closed
2109 $output .= $this->closeParagraph();
2110 if ( $preOpenMatch and !$preCloseMatch ) {
2111 $this->mInPre
= true;
2113 if ( $closematch ) {
2114 $inBlockElem = false;
2116 $inBlockElem = true;
2118 } else if ( !$inBlockElem && !$this->mInPre
) {
2119 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2121 if ($this->mLastSection
!== 'pre') {
2122 $paragraphStack = false;
2123 $output .= $this->closeParagraph().'<pre>';
2124 $this->mLastSection
= 'pre';
2126 $t = substr( $t, 1 );
2129 if ( '' == trim($t) ) {
2130 if ( $paragraphStack ) {
2131 $output .= $paragraphStack.'<br />';
2132 $paragraphStack = false;
2133 $this->mLastSection
= 'p';
2135 if ($this->mLastSection
!== 'p' ) {
2136 $output .= $this->closeParagraph();
2137 $this->mLastSection
= '';
2138 $paragraphStack = '<p>';
2140 $paragraphStack = '</p><p>';
2144 if ( $paragraphStack ) {
2145 $output .= $paragraphStack;
2146 $paragraphStack = false;
2147 $this->mLastSection
= 'p';
2148 } else if ($this->mLastSection
!== 'p') {
2149 $output .= $this->closeParagraph().'<p>';
2150 $this->mLastSection
= 'p';
2155 wfProfileOut( __METHOD__
."-paragraph" );
2157 // somewhere above we forget to get out of pre block (bug 785)
2158 if($preCloseMatch && $this->mInPre
) {
2159 $this->mInPre
= false;
2161 if ($paragraphStack === false) {
2165 while ( $prefixLength ) {
2166 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2169 if ( '' != $this->mLastSection
) {
2170 $output .= '</' . $this->mLastSection
. '>';
2171 $this->mLastSection
= '';
2174 wfProfileOut( __METHOD__
);
2179 * Split up a string on ':', ignoring any occurences inside tags
2180 * to prevent illegal overlapping.
2181 * @param string $str the string to split
2182 * @param string &$before set to everything before the ':'
2183 * @param string &$after set to everything after the ':'
2184 * return string the position of the ':', or false if none found
2186 function findColonNoLinks($str, &$before, &$after) {
2187 wfProfileIn( __METHOD__
);
2189 $pos = strpos( $str, ':' );
2190 if( $pos === false ) {
2192 wfProfileOut( __METHOD__
);
2196 $lt = strpos( $str, '<' );
2197 if( $lt === false ||
$lt > $pos ) {
2198 // Easy; no tag nesting to worry about
2199 $before = substr( $str, 0, $pos );
2200 $after = substr( $str, $pos+
1 );
2201 wfProfileOut( __METHOD__
);
2205 // Ugly state machine to walk through avoiding tags.
2206 $state = self
::COLON_STATE_TEXT
;
2208 $len = strlen( $str );
2209 for( $i = 0; $i < $len; $i++
) {
2213 // (Using the number is a performance hack for common cases)
2214 case 0: // self::COLON_STATE_TEXT:
2217 // Could be either a <start> tag or an </end> tag
2218 $state = self
::COLON_STATE_TAGSTART
;
2223 $before = substr( $str, 0, $i );
2224 $after = substr( $str, $i +
1 );
2225 wfProfileOut( __METHOD__
);
2228 // Embedded in a tag; don't break it.
2231 // Skip ahead looking for something interesting
2232 $colon = strpos( $str, ':', $i );
2233 if( $colon === false ) {
2234 // Nothing else interesting
2235 wfProfileOut( __METHOD__
);
2238 $lt = strpos( $str, '<', $i );
2239 if( $stack === 0 ) {
2240 if( $lt === false ||
$colon < $lt ) {
2242 $before = substr( $str, 0, $colon );
2243 $after = substr( $str, $colon +
1 );
2244 wfProfileOut( __METHOD__
);
2248 if( $lt === false ) {
2249 // Nothing else interesting to find; abort!
2250 // We're nested, but there's no close tags left. Abort!
2253 // Skip ahead to next tag start
2255 $state = self
::COLON_STATE_TAGSTART
;
2258 case 1: // self::COLON_STATE_TAG:
2263 $state = self
::COLON_STATE_TEXT
;
2266 // Slash may be followed by >?
2267 $state = self
::COLON_STATE_TAGSLASH
;
2273 case 2: // self::COLON_STATE_TAGSTART:
2276 $state = self
::COLON_STATE_CLOSETAG
;
2279 $state = self
::COLON_STATE_COMMENT
;
2282 // Illegal early close? This shouldn't happen D:
2283 $state = self
::COLON_STATE_TEXT
;
2286 $state = self
::COLON_STATE_TAG
;
2289 case 3: // self::COLON_STATE_CLOSETAG:
2294 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2295 wfProfileOut( __METHOD__
);
2298 $state = self
::COLON_STATE_TEXT
;
2301 case self
::COLON_STATE_TAGSLASH
:
2303 // Yes, a self-closed tag <blah/>
2304 $state = self
::COLON_STATE_TEXT
;
2306 // Probably we're jumping the gun, and this is an attribute
2307 $state = self
::COLON_STATE_TAG
;
2310 case 5: // self::COLON_STATE_COMMENT:
2312 $state = self
::COLON_STATE_COMMENTDASH
;
2315 case self
::COLON_STATE_COMMENTDASH
:
2317 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2319 $state = self
::COLON_STATE_COMMENT
;
2322 case self
::COLON_STATE_COMMENTDASHDASH
:
2324 $state = self
::COLON_STATE_TEXT
;
2326 $state = self
::COLON_STATE_COMMENT
;
2330 throw new MWException( "State machine error in " . __METHOD__
);
2334 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2337 wfProfileOut( __METHOD__
);
2342 * Return value of a magic variable (like PAGENAME)
2346 function getVariableValue( $index ) {
2347 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2350 * Some of these require message or data lookups and can be
2351 * expensive to check many times.
2353 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2354 if ( isset( $this->mVarCache
[$index] ) ) {
2355 return $this->mVarCache
[$index];
2359 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2360 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2363 global $wgLocaltimezone;
2364 if ( isset( $wgLocaltimezone ) ) {
2365 $oldtz = getenv( 'TZ' );
2366 putenv( 'TZ='.$wgLocaltimezone );
2369 wfSuppressWarnings(); // E_STRICT system time bitching
2370 $localTimestamp = date( 'YmdHis', $ts );
2371 $localMonth = date( 'm', $ts );
2372 $localMonthName = date( 'n', $ts );
2373 $localDay = date( 'j', $ts );
2374 $localDay2 = date( 'd', $ts );
2375 $localDayOfWeek = date( 'w', $ts );
2376 $localWeek = date( 'W', $ts );
2377 $localYear = date( 'Y', $ts );
2378 $localHour = date( 'H', $ts );
2379 if ( isset( $wgLocaltimezone ) ) {
2380 putenv( 'TZ='.$oldtz );
2382 wfRestoreWarnings();
2385 case 'currentmonth':
2386 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2387 case 'currentmonthname':
2388 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2389 case 'currentmonthnamegen':
2390 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2391 case 'currentmonthabbrev':
2392 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2394 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2396 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2398 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2399 case 'localmonthname':
2400 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2401 case 'localmonthnamegen':
2402 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2403 case 'localmonthabbrev':
2404 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2406 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2408 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2410 return wfEscapeWikiText( $this->mTitle
->getText() );
2412 return $this->mTitle
->getPartialURL();
2413 case 'fullpagename':
2414 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2415 case 'fullpagenamee':
2416 return $this->mTitle
->getPrefixedURL();
2418 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2419 case 'subpagenamee':
2420 return $this->mTitle
->getSubpageUrlForm();
2421 case 'basepagename':
2422 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2423 case 'basepagenamee':
2424 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2425 case 'talkpagename':
2426 if( $this->mTitle
->canTalk() ) {
2427 $talkPage = $this->mTitle
->getTalkPage();
2428 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2432 case 'talkpagenamee':
2433 if( $this->mTitle
->canTalk() ) {
2434 $talkPage = $this->mTitle
->getTalkPage();
2435 return $talkPage->getPrefixedUrl();
2439 case 'subjectpagename':
2440 $subjPage = $this->mTitle
->getSubjectPage();
2441 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2442 case 'subjectpagenamee':
2443 $subjPage = $this->mTitle
->getSubjectPage();
2444 return $subjPage->getPrefixedUrl();
2446 // Let the edit saving system know we should parse the page
2447 // *after* a revision ID has been assigned.
2448 $this->mOutput
->setFlag( 'vary-revision' );
2449 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2450 return $this->mRevisionId
;
2452 // Let the edit saving system know we should parse the page
2453 // *after* a revision ID has been assigned. This is for null edits.
2454 $this->mOutput
->setFlag( 'vary-revision' );
2455 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2456 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2457 case 'revisionday2':
2458 // Let the edit saving system know we should parse the page
2459 // *after* a revision ID has been assigned. This is for null edits.
2460 $this->mOutput
->setFlag( 'vary-revision' );
2461 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2462 return substr( $this->getRevisionTimestamp(), 6, 2 );
2463 case 'revisionmonth':
2464 // Let the edit saving system know we should parse the page
2465 // *after* a revision ID has been assigned. This is for null edits.
2466 $this->mOutput
->setFlag( 'vary-revision' );
2467 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2468 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2469 case 'revisionyear':
2470 // Let the edit saving system know we should parse the page
2471 // *after* a revision ID has been assigned. This is for null edits.
2472 $this->mOutput
->setFlag( 'vary-revision' );
2473 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2474 return substr( $this->getRevisionTimestamp(), 0, 4 );
2475 case 'revisiontimestamp':
2476 // Let the edit saving system know we should parse the page
2477 // *after* a revision ID has been assigned. This is for null edits.
2478 $this->mOutput
->setFlag( 'vary-revision' );
2479 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2480 return $this->getRevisionTimestamp();
2482 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2484 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2486 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2488 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2489 case 'subjectspace':
2490 return $this->mTitle
->getSubjectNsText();
2491 case 'subjectspacee':
2492 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2493 case 'currentdayname':
2494 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2496 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2498 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2500 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2502 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2503 // int to remove the padding
2504 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2506 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2507 case 'localdayname':
2508 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2510 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2512 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2514 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2516 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2517 // int to remove the padding
2518 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2520 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2521 case 'numberofarticles':
2522 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2523 case 'numberoffiles':
2524 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2525 case 'numberofusers':
2526 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2527 case 'numberofpages':
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2529 case 'numberofadmins':
2530 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2531 case 'numberofedits':
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2533 case 'currenttimestamp':
2534 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2535 case 'localtimestamp':
2536 return $this->mVarCache
[$index] = $localTimestamp;
2537 case 'currentversion':
2538 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2544 return $wgServerName;
2546 return $wgScriptPath;
2547 case 'directionmark':
2548 return $wgContLang->getDirMark();
2549 case 'contentlanguage':
2550 global $wgContLanguageCode;
2551 return $wgContLanguageCode;
2554 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2562 * initialise the magic variables (like CURRENTMONTHNAME)
2566 function initialiseVariables() {
2567 wfProfileIn( __METHOD__
);
2568 $variableIDs = MagicWord
::getVariableIDs();
2570 $this->mVariables
= new MagicWordArray( $variableIDs );
2571 wfProfileOut( __METHOD__
);
2575 * Preprocess some wikitext and return the document tree.
2576 * This is the ghost of replace_variables().
2578 * @param string $text The text to parse
2579 * @param integer flags Bitwise combination of:
2580 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2581 * included. Default is to assume a direct page view.
2583 * The generated DOM tree must depend only on the input text and the flags.
2584 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2586 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2587 * change in the DOM tree for a given text, must be passed through the section identifier
2588 * in the section edit link and thus back to extractSections().
2590 * The output of this function is currently only cached in process memory, but a persistent
2591 * cache may be implemented at a later date which takes further advantage of these strict
2592 * dependency requirements.
2596 function preprocessToDom ( $text, $flags = 0 ) {
2597 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2602 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2604 public static function splitWhitespace( $s ) {
2605 $ltrimmed = ltrim( $s );
2606 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2607 $trimmed = rtrim( $ltrimmed );
2608 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2610 $w2 = substr( $ltrimmed, -$diff );
2614 return array( $w1, $trimmed, $w2 );
2618 * Replace magic variables, templates, and template arguments
2619 * with the appropriate text. Templates are substituted recursively,
2620 * taking care to avoid infinite loops.
2622 * Note that the substitution depends on value of $mOutputType:
2623 * self::OT_WIKI: only {{subst:}} templates
2624 * self::OT_PREPROCESS: templates but not extension tags
2625 * self::OT_HTML: all templates and extension tags
2627 * @param string $tex The text to transform
2628 * @param PPFrame $frame Object describing the arguments passed to the template.
2629 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2630 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2631 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2634 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2635 # Prevent too big inclusions
2636 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2640 wfProfileIn( __METHOD__
);
2642 if ( $frame === false ) {
2643 $frame = $this->getPreprocessor()->newFrame();
2644 } elseif ( !( $frame instanceof PPFrame
) ) {
2645 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2646 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2649 $dom = $this->preprocessToDom( $text );
2650 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2651 $text = $frame->expand( $dom, $flags );
2653 wfProfileOut( __METHOD__
);
2657 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2658 static function createAssocArgs( $args ) {
2659 $assocArgs = array();
2661 foreach( $args as $arg ) {
2662 $eqpos = strpos( $arg, '=' );
2663 if ( $eqpos === false ) {
2664 $assocArgs[$index++
] = $arg;
2666 $name = trim( substr( $arg, 0, $eqpos ) );
2667 $value = trim( substr( $arg, $eqpos+
1 ) );
2668 if ( $value === false ) {
2671 if ( $name !== false ) {
2672 $assocArgs[$name] = $value;
2681 * Warn the user when a parser limitation is reached
2682 * Will warn at most once the user per limitation type
2684 * @param string $limitationType, should be one of:
2685 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2686 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2687 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2688 * @params int $current, $max When an explicit limit has been
2689 * exceeded, provide the values (optional)
2691 function limitationWarn( $limitationType, $current=null, $max=null) {
2692 $msgName = $limitationType . '-warning';
2693 //does no harm if $current and $max are present but are unnecessary for the message
2694 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2695 $this->mOutput
->addWarning( $warning );
2696 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2698 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2703 * Return the text of a template, after recursively
2704 * replacing any variables or templates within the template.
2706 * @param array $piece The parts of the template
2707 * $piece['title']: the title, i.e. the part before the |
2708 * $piece['parts']: the parameter array
2709 * $piece['lineStart']: whether the brace was at the start of a line
2710 * @param PPFrame The current frame, contains template arguments
2711 * @return string the text of the template
2714 function braceSubstitution( $piece, $frame ) {
2715 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2716 wfProfileIn( __METHOD__
);
2717 wfProfileIn( __METHOD__
.'-setup' );
2720 $found = false; # $text has been filled
2721 $nowiki = false; # wiki markup in $text should be escaped
2722 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2723 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2724 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2725 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2727 # Title object, where $text came from
2730 # $part1 is the bit before the first |, and must contain only title characters.
2731 # Various prefixes will be stripped from it later.
2732 $titleWithSpaces = $frame->expand( $piece['title'] );
2733 $part1 = trim( $titleWithSpaces );
2736 # Original title text preserved for various purposes
2737 $originalTitle = $part1;
2739 # $args is a list of argument nodes, starting from index 0, not including $part1
2740 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2741 wfProfileOut( __METHOD__
.'-setup' );
2744 wfProfileIn( __METHOD__
.'-modifiers' );
2746 $mwSubst = MagicWord
::get( 'subst' );
2747 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2748 # One of two possibilities is true:
2749 # 1) Found SUBST but not in the PST phase
2750 # 2) Didn't find SUBST and in the PST phase
2751 # In either case, return without further processing
2752 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2759 if ( !$found && $args->getLength() == 0 ) {
2760 $id = $this->mVariables
->matchStartToEnd( $part1 );
2761 if ( $id !== false ) {
2762 $text = $this->getVariableValue( $id );
2763 if (MagicWord
::getCacheTTL($id)>-1)
2764 $this->mOutput
->mContainsOldMagic
= true;
2769 # MSG, MSGNW and RAW
2772 $mwMsgnw = MagicWord
::get( 'msgnw' );
2773 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2776 # Remove obsolete MSG:
2777 $mwMsg = MagicWord
::get( 'msg' );
2778 $mwMsg->matchStartAndRemove( $part1 );
2782 $mwRaw = MagicWord
::get( 'raw' );
2783 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2784 $forceRawInterwiki = true;
2787 wfProfileOut( __METHOD__
.'-modifiers' );
2791 wfProfileIn( __METHOD__
. '-pfunc' );
2793 $colonPos = strpos( $part1, ':' );
2794 if ( $colonPos !== false ) {
2795 # Case sensitive functions
2796 $function = substr( $part1, 0, $colonPos );
2797 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2798 $function = $this->mFunctionSynonyms
[1][$function];
2800 # Case insensitive functions
2801 $function = strtolower( $function );
2802 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2803 $function = $this->mFunctionSynonyms
[0][$function];
2809 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2810 $initialArgs = array( &$this );
2811 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2812 if ( $flags & SFH_OBJECT_ARGS
) {
2813 # Add a frame parameter, and pass the arguments as an array
2814 $allArgs = $initialArgs;
2815 $allArgs[] = $frame;
2816 for ( $i = 0; $i < $args->getLength(); $i++
) {
2817 $funcArgs[] = $args->item( $i );
2819 $allArgs[] = $funcArgs;
2821 # Convert arguments to plain text
2822 for ( $i = 0; $i < $args->getLength(); $i++
) {
2823 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2825 $allArgs = array_merge( $initialArgs, $funcArgs );
2828 # Workaround for PHP bug 35229 and similar
2829 if ( !is_callable( $callback ) ) {
2830 throw new MWException( "Tag hook for $name is not callable\n" );
2832 $result = call_user_func_array( $callback, $allArgs );
2835 $preprocessFlags = 0;
2837 if ( is_array( $result ) ) {
2838 if ( isset( $result[0] ) ) {
2840 unset( $result[0] );
2843 // Extract flags into the local scope
2844 // This allows callers to set flags such as nowiki, found, etc.
2850 $text = $this->preprocessToDom( $text, $preprocessFlags );
2855 wfProfileOut( __METHOD__
. '-pfunc' );
2858 # Finish mangling title and then check for loops.
2859 # Set $title to a Title object and $titleText to the PDBK
2862 # Split the title into page and subpage
2864 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2865 if ($subpage !== '') {
2866 $ns = $this->mTitle
->getNamespace();
2868 $title = Title
::newFromText( $part1, $ns );
2870 $titleText = $title->getPrefixedText();
2871 # Check for language variants if the template is not found
2872 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2873 $wgContLang->findVariantLink( $part1, $title, true );
2875 # Do infinite loop check
2876 if ( !$frame->loopCheck( $title ) ) {
2878 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2879 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2881 # Do recursion depth check
2882 $limit = $this->mOptions
->getMaxTemplateDepth();
2883 if ( $frame->depth
>= $limit ) {
2885 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2890 # Load from database
2891 if ( !$found && $title ) {
2892 wfProfileIn( __METHOD__
. '-loadtpl' );
2893 if ( !$title->isExternal() ) {
2894 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2895 $text = SpecialPage
::capturePath( $title );
2896 if ( is_string( $text ) ) {
2899 $this->disableCache();
2901 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2902 $found = false; //access denied
2903 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2905 list( $text, $title ) = $this->getTemplateDom( $title );
2906 if ( $text !== false ) {
2912 # If the title is valid but undisplayable, make a link to it
2913 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2914 $text = "[[:$titleText]]";
2917 } elseif ( $title->isTrans() ) {
2918 // Interwiki transclusion
2919 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2920 $text = $this->interwikiTransclude( $title, 'render' );
2923 $text = $this->interwikiTransclude( $title, 'raw' );
2924 // Preprocess it like a template
2925 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2930 wfProfileOut( __METHOD__
. '-loadtpl' );
2933 # If we haven't found text to substitute by now, we're done
2934 # Recover the source wikitext and return it
2936 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2937 wfProfileOut( __METHOD__
);
2938 return array( 'object' => $text );
2941 # Expand DOM-style return values in a child frame
2942 if ( $isChildObj ) {
2943 # Clean up argument array
2944 $newFrame = $frame->newChild( $args, $title );
2947 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2948 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2949 # Expansion is eligible for the empty-frame cache
2950 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2951 $text = $this->mTplExpandCache
[$titleText];
2953 $text = $newFrame->expand( $text );
2954 $this->mTplExpandCache
[$titleText] = $text;
2957 # Uncached expansion
2958 $text = $newFrame->expand( $text );
2961 if ( $isLocalObj && $nowiki ) {
2962 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2963 $isLocalObj = false;
2966 # Replace raw HTML by a placeholder
2967 # Add a blank line preceding, to prevent it from mucking up
2968 # immediately preceding headings
2970 $text = "\n\n" . $this->insertStripItem( $text );
2972 # Escape nowiki-style return values
2973 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2974 $text = wfEscapeWikiText( $text );
2976 # Bug 529: if the template begins with a table or block-level
2977 # element, it should be treated as beginning a new line.
2978 # This behaviour is somewhat controversial.
2979 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2980 $text = "\n" . $text;
2983 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2984 # Error, oversize inclusion
2985 $text = "[[$originalTitle]]" .
2986 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2987 $this->limitationWarn( 'post-expand-template-inclusion' );
2990 if ( $isLocalObj ) {
2991 $ret = array( 'object' => $text );
2993 $ret = array( 'text' => $text );
2996 wfProfileOut( __METHOD__
);
3001 * Get the semi-parsed DOM representation of a template with a given title,
3002 * and its redirect destination title. Cached.
3004 function getTemplateDom( $title ) {
3005 $cacheTitle = $title;
3006 $titleText = $title->getPrefixedDBkey();
3008 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3009 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3010 $title = Title
::makeTitle( $ns, $dbk );
3011 $titleText = $title->getPrefixedDBkey();
3013 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3014 return array( $this->mTplDomCache
[$titleText], $title );
3017 // Cache miss, go to the database
3018 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3020 if ( $text === false ) {
3021 $this->mTplDomCache
[$titleText] = false;
3022 return array( false, $title );
3025 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3026 $this->mTplDomCache
[ $titleText ] = $dom;
3028 if (! $title->equals($cacheTitle)) {
3029 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3030 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3033 return array( $dom, $title );
3037 * Fetch the unparsed text of a template and register a reference to it.
3039 function fetchTemplateAndTitle( $title ) {
3040 $templateCb = $this->mOptions
->getTemplateCallback();
3041 $stuff = call_user_func( $templateCb, $title, $this );
3042 $text = $stuff['text'];
3043 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3044 if ( isset( $stuff['deps'] ) ) {
3045 foreach ( $stuff['deps'] as $dep ) {
3046 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3049 return array($text,$finalTitle);
3052 function fetchTemplate( $title ) {
3053 $rv = $this->fetchTemplateAndTitle($title);
3058 * Static function to get a template
3059 * Can be overridden via ParserOptions::setTemplateCallback().
3061 static function statelessFetchTemplate( $title, $parser=false ) {
3062 $text = $skip = false;
3063 $finalTitle = $title;
3066 // Loop to fetch the article, with up to 1 redirect
3067 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3068 # Give extensions a chance to select the revision instead
3069 $id = false; // Assume current
3070 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3076 'page_id' => $title->getArticleID(),
3080 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3081 $rev_id = $rev ?
$rev->getId() : 0;
3082 // If there is no current revision, there is no page
3083 if( $id === false && !$rev ) {
3084 $linkCache = LinkCache
::singleton();
3085 $linkCache->addBadLinkObj( $title );
3090 'page_id' => $title->getArticleID(),
3091 'rev_id' => $rev_id );
3094 $text = $rev->getText();
3095 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3097 $message = $wgLang->lcfirst( $title->getText() );
3098 $text = wfMsgForContentNoTrans( $message );
3099 if( wfEmptyMsg( $message, $text ) ) {
3106 if ( $text === false ) {
3110 $finalTitle = $title;
3111 $title = Title
::newFromRedirect( $text );
3115 'finalTitle' => $finalTitle,
3120 * Transclude an interwiki link.
3122 function interwikiTransclude( $title, $action ) {
3123 global $wgEnableScaryTranscluding;
3125 if (!$wgEnableScaryTranscluding)
3126 return wfMsg('scarytranscludedisabled');
3128 $url = $title->getFullUrl( "action=$action" );
3130 if (strlen($url) > 255)
3131 return wfMsg('scarytranscludetoolong');
3132 return $this->fetchScaryTemplateMaybeFromCache($url);
3135 function fetchScaryTemplateMaybeFromCache($url) {
3136 global $wgTranscludeCacheExpiry;
3137 $dbr = wfGetDB(DB_SLAVE
);
3138 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3139 array('tc_url' => $url));
3141 $time = $obj->tc_time
;
3142 $text = $obj->tc_contents
;
3143 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3148 $text = Http
::get($url);
3150 return wfMsg('scarytranscludefailed', $url);
3152 $dbw = wfGetDB(DB_MASTER
);
3153 $dbw->replace('transcache', array('tc_url'), array(
3155 'tc_time' => time(),
3156 'tc_contents' => $text));
3162 * Triple brace replacement -- used for template arguments
3165 function argSubstitution( $piece, $frame ) {
3166 wfProfileIn( __METHOD__
);
3169 $parts = $piece['parts'];
3170 $nameWithSpaces = $frame->expand( $piece['title'] );
3171 $argName = trim( $nameWithSpaces );
3173 $text = $frame->getArgument( $argName );
3174 if ( $text === false && $parts->getLength() > 0
3178 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3181 # No match in frame, use the supplied default
3182 $object = $parts->item( 0 )->getChildren();
3184 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3185 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3186 $this->limitationWarn( 'post-expand-template-argument' );
3189 if ( $text === false && $object === false ) {
3191 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3193 if ( $error !== false ) {
3196 if ( $object !== false ) {
3197 $ret = array( 'object' => $object );
3199 $ret = array( 'text' => $text );
3202 wfProfileOut( __METHOD__
);
3207 * Return the text to be used for a given extension tag.
3208 * This is the ghost of strip().
3210 * @param array $params Associative array of parameters:
3211 * name PPNode for the tag name
3212 * attr PPNode for unparsed text where tag attributes are thought to be
3213 * attributes Optional associative array of parsed attributes
3214 * inner Contents of extension element
3215 * noClose Original text did not have a close tag
3216 * @param PPFrame $frame
3218 function extensionSubstitution( $params, $frame ) {
3219 global $wgRawHtml, $wgContLang;
3221 $name = $frame->expand( $params['name'] );
3222 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3223 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3225 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3227 if ( $this->ot
['html'] ) {
3228 $name = strtolower( $name );
3230 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3231 if ( isset( $params['attributes'] ) ) {
3232 $attributes = $attributes +
$params['attributes'];
3240 throw new MWException( '<html> extension tag encountered unexpectedly' );
3243 $output = Xml
::escapeTagsOnly( $content );
3246 $output = $wgContLang->armourMath(
3247 MathRenderer
::renderMath( $content, $attributes ) );
3250 $output = $this->renderImageGallery( $content, $attributes );
3253 if( isset( $this->mTagHooks
[$name] ) ) {
3254 # Workaround for PHP bug 35229 and similar
3255 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3256 throw new MWException( "Tag hook for $name is not callable\n" );
3258 $output = call_user_func_array( $this->mTagHooks
[$name],
3259 array( $content, $attributes, $this ) );
3261 $output = '<span class="error">Invalid tag extension name: ' .
3262 htmlspecialchars( $name ) . '</span>';
3266 if ( is_null( $attrText ) ) {
3269 if ( isset( $params['attributes'] ) ) {
3270 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3271 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3272 htmlspecialchars( $attrValue ) . '"';
3275 if ( $content === null ) {
3276 $output = "<$name$attrText/>";
3278 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3279 $output = "<$name$attrText>$content$close";
3283 if ( $name === 'html' ||
$name === 'nowiki' ) {
3284 $this->mStripState
->nowiki
->setPair( $marker, $output );
3286 $this->mStripState
->general
->setPair( $marker, $output );
3292 * Increment an include size counter
3294 * @param string $type The type of expansion
3295 * @param integer $size The size of the text
3296 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3298 function incrementIncludeSize( $type, $size ) {
3299 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3302 $this->mIncludeSizes
[$type] +
= $size;
3308 * Increment the expensive function count
3310 * @return boolean False if the limit has been exceeded
3312 function incrementExpensiveFunctionCount() {
3313 global $wgExpensiveParserFunctionLimit;
3314 $this->mExpensiveFunctionCount++
;
3315 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3322 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3323 * Fills $this->mDoubleUnderscores, returns the modified text
3325 function doDoubleUnderscore( $text ) {
3326 // The position of __TOC__ needs to be recorded
3327 $mw = MagicWord
::get( 'toc' );
3328 if( $mw->match( $text ) ) {
3329 $this->mShowToc
= true;
3330 $this->mForceTocPosition
= true;
3332 // Set a placeholder. At the end we'll fill it in with the TOC.
3333 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3335 // Only keep the first one.
3336 $text = $mw->replace( '', $text );
3339 // Now match and remove the rest of them
3340 $mwa = MagicWord
::getDoubleUnderscoreArray();
3341 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3343 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3344 $this->mOutput
->mNoGallery
= true;
3346 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3347 $this->mShowToc
= false;
3349 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3350 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3352 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3353 if ( $containerCategory ) {
3354 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3356 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3359 # (bug 8068) Allow control over whether robots index a page.
3361 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3362 # is not desirable, the last one on the page should win.
3363 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3364 $this->mOutput
->setIndexPolicy( 'noindex' );
3365 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3366 $this->mOutput
->setIndexPolicy( 'index' );
3373 * This function accomplishes several tasks:
3374 * 1) Auto-number headings if that option is enabled
3375 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3376 * 3) Add a Table of contents on the top for users who have enabled the option
3377 * 4) Auto-anchor headings
3379 * It loops through all headlines, collects the necessary data, then splits up the
3380 * string and re-inserts the newly formatted headlines.
3382 * @param string $text
3383 * @param boolean $isMain
3386 function formatHeadings( $text, $isMain=true ) {
3387 global $wgMaxTocLevel, $wgContLang;
3389 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3390 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3393 $showEditLink = $this->mOptions
->getEditSection();
3396 # Inhibit editsection links if requested in the page
3397 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3401 # Get all headlines for numbering them and adding funky stuff like [edit]
3402 # links - this is for later, but we need the number of headlines right now
3404 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3406 # if there are fewer than 4 headlines in the article, do not show TOC
3407 # unless it's been explicitly enabled.
3408 $enoughToc = $this->mShowToc
&&
3409 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3411 # Allow user to stipulate that a page should have a "new section"
3412 # link added via __NEWSECTIONLINK__
3413 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3414 $this->mOutput
->setNewSection( true );
3417 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3418 # override above conditions and always show TOC above first header
3419 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3420 $this->mShowToc
= true;
3424 # We need this to perform operations on the HTML
3425 $sk = $this->mOptions
->getSkin();
3431 # Ugh .. the TOC should have neat indentation levels which can be
3432 # passed to the skin functions. These are determined here
3436 $sublevelCount = array();
3437 $levelCount = array();
3443 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3444 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3447 foreach( $matches[3] as $headline ) {
3448 $isTemplate = false;
3450 $sectionIndex = false;
3452 $markerMatches = array();
3453 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3454 $serial = $markerMatches[1];
3455 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3456 $isTemplate = ($titleText != $baseTitleText);
3457 $headline = preg_replace("/^$markerRegex/", "", $headline);
3461 $prevlevel = $level;
3462 $prevtoclevel = $toclevel;
3464 $level = $matches[1][$headlineCount];
3466 if( $doNumberHeadings ||
$enoughToc ) {
3468 if ( $level > $prevlevel ) {
3469 # Increase TOC level
3471 $sublevelCount[$toclevel] = 0;
3472 if( $toclevel<$wgMaxTocLevel ) {
3473 $prevtoclevel = $toclevel;
3474 $toc .= $sk->tocIndent();
3478 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3479 # Decrease TOC level, find level to jump to
3481 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3482 # Can only go down to level 1
3485 for ($i = $toclevel; $i > 0; $i--) {
3486 if ( $levelCount[$i] == $level ) {
3487 # Found last matching level
3491 elseif ( $levelCount[$i] < $level ) {
3492 # Found first matching level below current level
3498 if( $toclevel<$wgMaxTocLevel ) {
3499 if($prevtoclevel < $wgMaxTocLevel) {
3500 # Unindent only if the previous toc level was shown :p
3501 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3502 $prevtoclevel = $toclevel;
3504 $toc .= $sk->tocLineEnd();
3509 # No change in level, end TOC line
3510 if( $toclevel<$wgMaxTocLevel ) {
3511 $toc .= $sk->tocLineEnd();
3515 $levelCount[$toclevel] = $level;
3517 # count number of headlines for each level
3518 @$sublevelCount[$toclevel]++
;
3520 for( $i = 1; $i <= $toclevel; $i++
) {
3521 if( !empty( $sublevelCount[$i] ) ) {
3525 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3531 # The safe header is a version of the header text safe to use for links
3532 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3533 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3535 # Remove link placeholders by the link text.
3536 # <!--LINK number-->
3538 # link text with suffix
3539 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3541 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3542 $tocline = preg_replace(
3543 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3547 $tocline = trim( $tocline );
3549 # For the anchor, strip out HTML-y stuff period
3550 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3551 $safeHeadline = trim( $safeHeadline );
3553 # Save headline for section edit hint before it's escaped
3554 $headlineHint = $safeHeadline;
3555 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3556 # HTML names must be case-insensitively unique (bug 10721)
3557 $arrayKey = strtolower( $safeHeadline );
3559 # count how many in assoc. array so we can track dupes in anchors
3560 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3561 $refcount[$headlineCount] = $refers[$arrayKey];
3563 # Don't number the heading if it is the only one (looks silly)
3564 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3565 # the two are different if the line contains a link
3566 $headline=$numbering . ' ' . $headline;
3569 # Create the anchor for linking from the TOC to the section
3570 $anchor = $safeHeadline;
3571 if($refcount[$headlineCount] > 1 ) {
3572 $anchor .= '_' . $refcount[$headlineCount];
3574 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3575 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3576 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3578 # give headline the correct <h#> tag
3579 if( $showEditLink && $sectionIndex !== false ) {
3581 # Put a T flag in the section identifier, to indicate to extractSections()
3582 # that sections inside <includeonly> should be counted.
3583 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3585 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3590 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3595 $this->mOutput
->setSections( $tocraw );
3597 # Never ever show TOC if no headers
3598 if( $numVisible < 1 ) {
3603 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3604 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3606 $toc = $sk->tocList( $toc );
3609 # split up and insert constructed headlines
3611 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3614 foreach( $blocks as $block ) {
3615 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3616 # This is the [edit] link that appears for the top block of text when
3617 # section editing is enabled
3619 # Disabled because it broke block formatting
3620 # For example, a bullet point in the top line
3621 # $full .= $sk->editSectionLink(0);
3624 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3625 # Top anchor now in skin
3629 if( !empty( $head[$i] ) ) {
3634 if( $this->mForceTocPosition
) {
3635 return str_replace( '<!--MWTOC-->', $toc, $full );
3642 * Transform wiki markup when saving a page by doing \r\n -> \n
3643 * conversion, substitting signatures, {{subst:}} templates, etc.
3645 * @param string $text the text to transform
3646 * @param Title &$title the Title object for the current article
3647 * @param User &$user the User object describing the current user
3648 * @param ParserOptions $options parsing options
3649 * @param bool $clearState whether to clear the parser state first
3650 * @return string the altered wiki markup
3653 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3654 $this->mOptions
= $options;
3655 $this->setTitle( $title );
3656 $this->setOutputType( self
::OT_WIKI
);
3658 if ( $clearState ) {
3659 $this->clearState();
3665 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3666 $text = $this->pstPass2( $text, $user );
3667 $text = $this->mStripState
->unstripBoth( $text );
3672 * Pre-save transform helper function
3675 function pstPass2( $text, $user ) {
3676 global $wgContLang, $wgLocaltimezone;
3678 /* Note: This is the timestamp saved as hardcoded wikitext to
3679 * the database, we use $wgContLang here in order to give
3680 * everyone the same signature and use the default one rather
3681 * than the one selected in each user's preferences.
3683 * (see also bug 12815)
3685 $ts = $this->mOptions
->getTimestamp();
3686 $tz = wfMsgForContent( 'timezone-utc' );
3687 if ( isset( $wgLocaltimezone ) ) {
3688 $unixts = wfTimestamp( TS_UNIX
, $ts );
3689 $oldtz = getenv( 'TZ' );
3690 putenv( 'TZ='.$wgLocaltimezone );
3691 $ts = date( 'YmdHis', $unixts );
3692 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3693 putenv( 'TZ='.$oldtz );
3696 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3698 # Variable replacement
3699 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3700 $text = $this->replaceVariables( $text );
3703 $sigText = $this->getUserSig( $user );
3704 $text = strtr( $text, array(
3706 '~~~~' => "$sigText $d",
3710 # Context links: [[|name]] and [[name (context)|]]
3712 global $wgLegalTitleChars;
3713 $tc = "[$wgLegalTitleChars]";
3714 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3716 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3717 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3718 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3719 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3721 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3722 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3723 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3724 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3726 $t = $this->mTitle
->getText();
3728 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3729 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3730 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3731 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3733 # if there's no context, don't bother duplicating the title
3734 $text = preg_replace( $p2, '[[\\1]]', $text );
3737 # Trim trailing whitespace
3738 $text = rtrim( $text );
3744 * Fetch the user's signature text, if any, and normalize to
3745 * validated, ready-to-insert wikitext.
3751 function getUserSig( &$user ) {
3752 global $wgMaxSigChars;
3754 $username = $user->getName();
3755 $nickname = $user->getOption( 'nickname' );
3756 $nickname = $nickname === '' ?
$username : $nickname;
3758 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3759 $nickname = $username;
3760 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3761 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3762 # Sig. might contain markup; validate this
3763 if( $this->validateSig( $nickname ) !== false ) {
3764 # Validated; clean up (if needed) and return it
3765 return $this->cleanSig( $nickname, true );
3767 # Failed to validate; fall back to the default
3768 $nickname = $username;
3769 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3773 // Make sure nickname doesnt get a sig in a sig
3774 $nickname = $this->cleanSigInSig( $nickname );
3776 # If we're still here, make it a link to the user page
3777 $userText = wfEscapeWikiText( $username );
3778 $nickText = wfEscapeWikiText( $nickname );
3779 if ( $user->isAnon() ) {
3780 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3782 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3787 * Check that the user's signature contains no bad XML
3789 * @param string $text
3790 * @return mixed An expanded string, or false if invalid.
3792 function validateSig( $text ) {
3793 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3797 * Clean up signature text
3799 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3800 * 2) Substitute all transclusions
3802 * @param string $text
3803 * @param $parsing Whether we're cleaning (preferences save) or parsing
3804 * @return string Signature text
3806 function cleanSig( $text, $parsing = false ) {
3809 $this->clearState();
3810 $this->setTitle( $wgTitle );
3811 $this->mOptions
= new ParserOptions
;
3812 $this->setOutputType
= self
::OT_PREPROCESS
;
3815 # Option to disable this feature
3816 if ( !$this->mOptions
->getCleanSignatures() ) {
3820 # FIXME: regex doesn't respect extension tags or nowiki
3821 # => Move this logic to braceSubstitution()
3822 $substWord = MagicWord
::get( 'subst' );
3823 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3824 $substText = '{{' . $substWord->getSynonym( 0 );
3826 $text = preg_replace( $substRegex, $substText, $text );
3827 $text = $this->cleanSigInSig( $text );
3828 $dom = $this->preprocessToDom( $text );
3829 $frame = $this->getPreprocessor()->newFrame();
3830 $text = $frame->expand( $dom );
3833 $text = $this->mStripState
->unstripBoth( $text );
3840 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3841 * @param string $text
3842 * @return string Signature text with /~{3,5}/ removed
3844 function cleanSigInSig( $text ) {
3845 $text = preg_replace( '/~{3,5}/', '', $text );
3850 * Set up some variables which are usually set up in parse()
3851 * so that an external function can call some class members with confidence
3854 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3855 $this->setTitle( $title );
3856 $this->mOptions
= $options;
3857 $this->setOutputType( $outputType );
3858 if ( $clearState ) {
3859 $this->clearState();
3864 * Wrapper for preprocess()
3866 * @param string $text the text to preprocess
3867 * @param ParserOptions $options options
3871 function transformMsg( $text, $options ) {
3873 static $executing = false;
3875 # Guard against infinite recursion
3881 wfProfileIn(__METHOD__
);
3882 $text = $this->preprocess( $text, $wgTitle, $options );
3885 wfProfileOut(__METHOD__
);
3890 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3891 * The callback should have the following form:
3892 * function myParserHook( $text, $params, &$parser ) { ... }
3894 * Transform and return $text. Use $parser for any required context, e.g. use
3895 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3899 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3900 * @param mixed $callback The callback function (and object) to use for the tag
3902 * @return The old value of the mTagHooks array associated with the hook
3904 function setHook( $tag, $callback ) {
3905 $tag = strtolower( $tag );
3906 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3907 $this->mTagHooks
[$tag] = $callback;
3908 if( !in_array( $tag, $this->mStripList
) ) {
3909 $this->mStripList
[] = $tag;
3915 function setTransparentTagHook( $tag, $callback ) {
3916 $tag = strtolower( $tag );
3917 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3918 $this->mTransparentTagHooks
[$tag] = $callback;
3924 * Remove all tag hooks
3926 function clearTagHooks() {
3927 $this->mTagHooks
= array();
3928 $this->mStripList
= $this->mDefaultStripList
;
3932 * Create a function, e.g. {{sum:1|2|3}}
3933 * The callback function should have the form:
3934 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3936 * Or with SFH_OBJECT_ARGS:
3937 * function myParserFunction( $parser, $frame, $args ) { ... }
3939 * The callback may either return the text result of the function, or an array with the text
3940 * in element 0, and a number of flags in the other elements. The names of the flags are
3941 * specified in the keys. Valid flags are:
3942 * found The text returned is valid, stop processing the template. This
3944 * nowiki Wiki markup in the return value should be escaped
3945 * isHTML The returned text is HTML, armour it against wikitext transformation
3949 * @param string $id The magic word ID
3950 * @param mixed $callback The callback function (and object) to use
3951 * @param integer $flags a combination of the following flags:
3952 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3954 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3955 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3956 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3957 * the arguments, and to control the way they are expanded.
3959 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3960 * arguments, for instance:
3961 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3963 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3964 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3965 * working if/when this is changed.
3967 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3970 * Please read the documentation in includes/parser/Preprocessor.php for more information
3971 * about the methods available in PPFrame and PPNode.
3973 * @return The old callback function for this name, if any
3975 function setFunctionHook( $id, $callback, $flags = 0 ) {
3976 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3977 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3979 # Add to function cache
3980 $mw = MagicWord
::get( $id );
3982 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
3984 $synonyms = $mw->getSynonyms();
3985 $sensitive = intval( $mw->isCaseSensitive() );
3987 foreach ( $synonyms as $syn ) {
3989 if ( !$sensitive ) {
3990 $syn = strtolower( $syn );
3993 if ( !( $flags & SFH_NO_HASH
) ) {
3996 # Remove trailing colon
3997 if ( substr( $syn, -1, 1 ) === ':' ) {
3998 $syn = substr( $syn, 0, -1 );
4000 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4006 * Get all registered function hook identifiers
4010 function getFunctionHooks() {
4011 return array_keys( $this->mFunctionHooks
);
4015 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4016 * Placeholders created in Skin::makeLinkObj()
4017 * Returns an array of link CSS classes, indexed by PDBK.
4019 function replaceLinkHolders( &$text, $options = 0 ) {
4020 return $this->mLinkHolders
->replace( $text );
4024 * Replace <!--LINK--> link placeholders with plain text of links
4025 * (not HTML-formatted).
4026 * @param string $text
4029 function replaceLinkHoldersText( $text ) {
4030 return $this->mLinkHolders
->replaceText( $text );
4034 * Tag hook handler for 'pre'.
4036 function renderPreTag( $text, $attribs ) {
4037 // Backwards-compatibility hack
4038 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4040 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4041 return wfOpenElement( 'pre', $attribs ) .
4042 Xml
::escapeTagsOnly( $content ) .
4047 * Renders an image gallery from a text with one line per image.
4048 * text labels may be given by using |-style alternative text. E.g.
4049 * Image:one.jpg|The number "1"
4050 * Image:tree.jpg|A tree
4051 * given as text will return the HTML of a gallery with two images,
4052 * labeled 'The number "1"' and
4055 function renderImageGallery( $text, $params ) {
4056 $ig = new ImageGallery();
4057 $ig->setContextTitle( $this->mTitle
);
4058 $ig->setShowBytes( false );
4059 $ig->setShowFilename( false );
4060 $ig->setParser( $this );
4061 $ig->setHideBadImages();
4062 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4063 $ig->useSkin( $this->mOptions
->getSkin() );
4064 $ig->mRevisionId
= $this->mRevisionId
;
4066 if( isset( $params['caption'] ) ) {
4067 $caption = $params['caption'];
4068 $caption = htmlspecialchars( $caption );
4069 $caption = $this->replaceInternalLinks( $caption );
4070 $ig->setCaptionHtml( $caption );
4072 if( isset( $params['perrow'] ) ) {
4073 $ig->setPerRow( $params['perrow'] );
4075 if( isset( $params['widths'] ) ) {
4076 $ig->setWidths( $params['widths'] );
4078 if( isset( $params['heights'] ) ) {
4079 $ig->setHeights( $params['heights'] );
4082 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4084 $lines = StringUtils
::explode( "\n", $text );
4085 foreach ( $lines as $line ) {
4086 # match lines like these:
4087 # Image:someimage.jpg|This is some image
4089 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4091 if ( count( $matches ) == 0 ) {
4095 if ( strpos( $matches[0], '%' ) !== false )
4096 $matches[1] = urldecode( $matches[1] );
4097 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4099 if( is_null( $nt ) ) {
4100 # Bogus title. Ignore these so we don't bomb out later.
4103 if ( isset( $matches[3] ) ) {
4104 $label = $matches[3];
4109 $html = $this->recursiveTagParse( trim( $label ) );
4111 $ig->add( $nt, $html );
4113 # Only add real images (bug #5586)
4114 if ( $nt->getNamespace() == NS_IMAGE
) {
4115 $this->mOutput
->addImage( $nt->getDBkey() );
4118 return $ig->toHTML();
4121 function getImageParams( $handler ) {
4123 $handlerClass = get_class( $handler );
4127 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4128 // Initialise static lists
4129 static $internalParamNames = array(
4130 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4131 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4132 'bottom', 'text-bottom' ),
4133 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4134 'upright', 'border' ),
4136 static $internalParamMap;
4137 if ( !$internalParamMap ) {
4138 $internalParamMap = array();
4139 foreach ( $internalParamNames as $type => $names ) {
4140 foreach ( $names as $name ) {
4141 $magicName = str_replace( '-', '_', "img_$name" );
4142 $internalParamMap[$magicName] = array( $type, $name );
4147 // Add handler params
4148 $paramMap = $internalParamMap;
4150 $handlerParamMap = $handler->getParamMap();
4151 foreach ( $handlerParamMap as $magic => $paramName ) {
4152 $paramMap[$magic] = array( 'handler', $paramName );
4155 $this->mImageParams
[$handlerClass] = $paramMap;
4156 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4158 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4162 * Parse image options text and use it to make an image
4163 * @param Title $title
4164 * @param string $options
4165 * @param LinkHolderArray $holders
4167 function makeImage( $title, $options, $holders = false ) {
4168 # Check if the options text is of the form "options|alt text"
4170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4171 # * left no resizing, just left align. label is used for alt= only
4172 # * right same, but right aligned
4173 # * none same, but not aligned
4174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4175 # * center center the image
4176 # * framed Keep original image size, no magnify-button.
4177 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4178 # * upright reduce width for upright images, rounded to full __0 px
4179 # * border draw a 1px border around the image
4180 # vertical-align values (no % or length right now):
4190 $parts = StringUtils
::explode( "|", $options );
4191 $sk = $this->mOptions
->getSkin();
4193 # Give extensions a chance to select the file revision for us
4194 $skip = $time = $descQuery = false;
4195 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4198 return $sk->link( $title );
4202 $file = wfFindFile( $title, $time );
4203 $handler = $file ?
$file->getHandler() : false;
4205 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4207 # Process the input parameters
4209 $params = array( 'frame' => array(), 'handler' => array(),
4210 'horizAlign' => array(), 'vertAlign' => array() );
4211 foreach( $parts as $part ) {
4212 $part = trim( $part );
4213 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4215 if( isset( $paramMap[$magicName] ) ) {
4216 list( $type, $paramName ) = $paramMap[$magicName];
4218 // Special case; width and height come in one variable together
4219 if( $type === 'handler' && $paramName === 'width' ) {
4221 # (bug 13500) In both cases (width/height and width only),
4222 # permit trailing "px" for backward compatibility.
4223 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4224 $width = intval( $m[1] );
4225 $height = intval( $m[2] );
4226 if ( $handler->validateParam( 'width', $width ) ) {
4227 $params[$type]['width'] = $width;
4230 if ( $handler->validateParam( 'height', $height ) ) {
4231 $params[$type]['height'] = $height;
4234 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4235 $width = intval( $value );
4236 if ( $handler->validateParam( 'width', $width ) ) {
4237 $params[$type]['width'] = $width;
4240 } // else no validation -- bug 13436
4242 if ( $type === 'handler' ) {
4243 # Validate handler parameter
4244 $validated = $handler->validateParam( $paramName, $value );
4246 # Validate internal parameters
4247 switch( $paramName ) {
4249 /// @fixme - possibly check validity here?
4250 /// downstream behavior seems odd with missing manual thumbs.
4254 // Most other things appear to be empty or numeric...
4255 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4260 $params[$type][$paramName] = $value;
4264 if ( !$validated ) {
4269 # Process alignment parameters
4270 if ( $params['horizAlign'] ) {
4271 $params['frame']['align'] = key( $params['horizAlign'] );
4273 if ( $params['vertAlign'] ) {
4274 $params['frame']['valign'] = key( $params['vertAlign'] );
4277 # Strip bad stuff out of the alt text
4278 # We can't just use replaceLinkHoldersText() here, because if this function
4279 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4281 $alt = $holders->replaceText( $caption );
4283 $alt = $this->replaceLinkHoldersText( $caption );
4286 # make sure there are no placeholders in thumbnail attributes
4287 # that are later expanded to html- so expand them now and
4289 $alt = $this->mStripState
->unstripBoth( $alt );
4290 $alt = Sanitizer
::stripAllTags( $alt );
4292 $params['frame']['alt'] = $alt;
4293 $params['frame']['caption'] = $caption;
4295 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4297 # Linker does the rest
4298 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4300 # Give the handler a chance to modify the parser object
4302 $handler->parserTransformHook( $this, $file );
4309 * Set a flag in the output object indicating that the content is dynamic and
4310 * shouldn't be cached.
4312 function disableCache() {
4313 wfDebug( "Parser output marked as uncacheable.\n" );
4314 $this->mOutput
->mCacheTime
= -1;
4318 * Callback from the Sanitizer for expanding items found in HTML attribute
4319 * values, so they can be safely tested and escaped.
4320 * @param string $text
4321 * @param PPFrame $frame
4325 function attributeStripCallback( &$text, $frame = false ) {
4326 $text = $this->replaceVariables( $text, $frame );
4327 $text = $this->mStripState
->unstripBoth( $text );
4336 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4337 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4338 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4344 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4349 * Break wikitext input into sections, and either pull or replace
4350 * some particular section's text.
4352 * External callers should use the getSection and replaceSection methods.
4354 * @param string $text Page wikitext
4355 * @param string $section A section identifier string of the form:
4356 * <flag1> - <flag2> - ... - <section number>
4358 * Currently the only recognised flag is "T", which means the target section number
4359 * was derived during a template inclusion parse, in other words this is a template
4360 * section edit link. If no flags are given, it was an ordinary section edit link.
4361 * This flag is required to avoid a section numbering mismatch when a section is
4362 * enclosed by <includeonly> (bug 6563).
4364 * The section number 0 pulls the text before the first heading; other numbers will
4365 * pull the given section along with its lower-level subsections. If the section is
4366 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4368 * @param string $mode One of "get" or "replace"
4369 * @param string $newText Replacement text for section data.
4370 * @return string for "get", the extracted section text.
4371 * for "replace", the whole page with the section replaced.
4373 private function extractSections( $text, $section, $mode, $newText='' ) {
4375 $this->clearState();
4376 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4377 $this->mOptions
= new ParserOptions
;
4378 $this->setOutputType( self
::OT_WIKI
);
4380 $frame = $this->getPreprocessor()->newFrame();
4382 // Process section extraction flags
4384 $sectionParts = explode( '-', $section );
4385 $sectionIndex = array_pop( $sectionParts );
4386 foreach ( $sectionParts as $part ) {
4387 if ( $part === 'T' ) {
4388 $flags |
= self
::PTD_FOR_INCLUSION
;
4391 // Preprocess the text
4392 $root = $this->preprocessToDom( $text, $flags );
4394 // <h> nodes indicate section breaks
4395 // They can only occur at the top level, so we can find them by iterating the root's children
4396 $node = $root->getFirstChild();
4398 // Find the target section
4399 if ( $sectionIndex == 0 ) {
4400 // Section zero doesn't nest, level=big
4401 $targetLevel = 1000;
4404 if ( $node->getName() === 'h' ) {
4405 $bits = $node->splitHeading();
4406 if ( $bits['i'] == $sectionIndex ) {
4407 $targetLevel = $bits['level'];
4411 if ( $mode === 'replace' ) {
4412 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4414 $node = $node->getNextSibling();
4420 if ( $mode === 'get' ) {
4427 // Find the end of the section, including nested sections
4429 if ( $node->getName() === 'h' ) {
4430 $bits = $node->splitHeading();
4431 $curLevel = $bits['level'];
4432 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4436 if ( $mode === 'get' ) {
4437 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4439 $node = $node->getNextSibling();
4442 // Write out the remainder (in replace mode only)
4443 if ( $mode === 'replace' ) {
4444 // Output the replacement text
4445 // Add two newlines on -- trailing whitespace in $newText is conventionally
4446 // stripped by the editor, so we need both newlines to restore the paragraph gap
4447 $outText .= $newText . "\n\n";
4449 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4450 $node = $node->getNextSibling();
4454 if ( is_string( $outText ) ) {
4455 // Re-insert stripped tags
4456 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4463 * This function returns the text of a section, specified by a number ($section).
4464 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4465 * the first section before any such heading (section 0).
4467 * If a section contains subsections, these are also returned.
4469 * @param string $text text to look in
4470 * @param string $section section identifier
4471 * @param string $deftext default to return if section is not found
4472 * @return string text of the requested section
4474 public function getSection( $text, $section, $deftext='' ) {
4475 return $this->extractSections( $text, $section, "get", $deftext );
4478 public function replaceSection( $oldtext, $section, $text ) {
4479 return $this->extractSections( $oldtext, $section, "replace", $text );
4483 * Get the timestamp associated with the current revision, adjusted for
4484 * the default server-local timestamp
4486 function getRevisionTimestamp() {
4487 if ( is_null( $this->mRevisionTimestamp
) ) {
4488 wfProfileIn( __METHOD__
);
4490 $dbr = wfGetDB( DB_SLAVE
);
4491 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4492 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4494 // Normalize timestamp to internal MW format for timezone processing.
4495 // This has the added side-effect of replacing a null value with
4496 // the current time, which gives us more sensible behavior for
4498 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4500 // The cryptic '' timezone parameter tells to use the site-default
4501 // timezone offset instead of the user settings.
4503 // Since this value will be saved into the parser cache, served
4504 // to other users, and potentially even used inside links and such,
4505 // it needs to be consistent for all visitors.
4506 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4508 wfProfileOut( __METHOD__
);
4510 return $this->mRevisionTimestamp
;
4514 * Mutator for $mDefaultSort
4516 * @param $sort New value
4518 public function setDefaultSort( $sort ) {
4519 $this->mDefaultSort
= $sort;
4523 * Accessor for $mDefaultSort
4524 * Will use the title/prefixed title if none is set
4528 public function getDefaultSort() {
4529 global $wgCategoryPrefixedDefaultSortkey;
4530 if( $this->mDefaultSort
!== false ) {
4531 return $this->mDefaultSort
;
4532 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4533 !$wgCategoryPrefixedDefaultSortkey) {
4534 return $this->mTitle
->getText();
4536 return $this->mTitle
->getPrefixedText();
4541 * Try to guess the section anchor name based on a wikitext fragment
4542 * presumably extracted from a heading, for example "Header" from
4545 public function guessSectionNameFromWikiText( $text ) {
4546 # Strip out wikitext links(they break the anchor)
4547 $text = $this->stripSectionName( $text );
4548 $headline = Sanitizer
::decodeCharReferences( $text );
4550 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4551 $headline = trim( $headline );
4552 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4553 $replacearray = array(
4558 array_keys( $replacearray ),
4559 array_values( $replacearray ),
4564 * Strips a text string of wikitext for use in a section anchor
4566 * Accepts a text string and then removes all wikitext from the
4567 * string and leaves only the resultant text (i.e. the result of
4568 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4569 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4570 * to create valid section anchors by mimicing the output of the
4571 * parser when headings are parsed.
4573 * @param $text string Text string to be stripped of wikitext
4574 * for use in a Section anchor
4575 * @return Filtered text string
4577 public function stripSectionName( $text ) {
4578 # Strip internal link markup
4579 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4580 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4582 # Strip external link markup (FIXME: Not Tolerant to blank link text
4583 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4584 # on how many empty links there are on the page - need to figure that out.
4585 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4587 # Parse wikitext quotes (italics & bold)
4588 $text = $this->doQuotes($text);
4591 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4595 function srvus( $text ) {
4596 return $this->testSrvus( $text, $this->mOutputType
);
4600 * strip/replaceVariables/unstrip for preprocessor regression testing
4602 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4603 $this->clearState();
4604 if ( ! ( $title instanceof Title
) ) {
4605 $title = Title
::newFromText( $title );
4607 $this->mTitle
= $title;
4608 $this->mOptions
= $options;
4609 $this->setOutputType( $outputType );
4610 $text = $this->replaceVariables( $text );
4611 $text = $this->mStripState
->unstripBoth( $text );
4612 $text = Sanitizer
::removeHTMLtags( $text );
4616 function testPst( $text, $title, $options ) {
4618 if ( ! ( $title instanceof Title
) ) {
4619 $title = Title
::newFromText( $title );
4621 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4624 function testPreprocess( $text, $title, $options ) {
4625 if ( ! ( $title instanceof Title
) ) {
4626 $title = Title
::newFromText( $title );
4628 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4631 function markerSkipCallback( $s, $callback ) {
4634 while ( $i < strlen( $s ) ) {
4635 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4636 if ( $markerStart === false ) {
4637 $out .= call_user_func( $callback, substr( $s, $i ) );
4640 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4641 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4642 if ( $markerEnd === false ) {
4643 $out .= substr( $s, $markerStart );
4646 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4647 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4657 * @todo document, briefly.
4661 var $general, $nowiki;
4663 function __construct() {
4664 $this->general
= new ReplacementArray
;
4665 $this->nowiki
= new ReplacementArray
;
4668 function unstripGeneral( $text ) {
4669 wfProfileIn( __METHOD__
);
4672 $text = $this->general
->replace( $text );
4673 } while ( $text !== $oldText );
4674 wfProfileOut( __METHOD__
);
4678 function unstripNoWiki( $text ) {
4679 wfProfileIn( __METHOD__
);
4682 $text = $this->nowiki
->replace( $text );
4683 } while ( $text !== $oldText );
4684 wfProfileOut( __METHOD__
);
4688 function unstripBoth( $text ) {
4689 wfProfileIn( __METHOD__
);
4692 $text = $this->general
->replace( $text );
4693 $text = $this->nowiki
->replace( $text );
4694 } while ( $text !== $oldText );
4695 wfProfileOut( __METHOD__
);
4701 * @todo document, briefly.
4704 class OnlyIncludeReplacer
{
4707 function replace( $matches ) {
4708 if ( substr( $matches[1], -1 ) === "\n" ) {
4709 $this->output
.= substr( $matches[1], 0, -1 );
4711 $this->output
.= $matches[1];